|
Этот совет Java иллюстрирует метод извлечения файла из сжатого файла ZIP. Этот пример читает файл ZIP и распаковывает первого въезда. Разработчик может изменять код в соответствии с его потребностями.
try {
// Open the ZIP file
String sourcefile = "source.zip";
ZipInputStream in = new ZipInputStream(new FileInputStream(sourcefile));
// Get the first entry
ZipEntry entry = in.getNextEntry();
// Open the output file
String targetfile = "target";
OutputStream out = new FileOutputStream(targetfile);
// Transfer bytes from the ZIP file to the output file
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Close the streams
out.close();
in.close();
} catch (IOException e) {
}
|
|
|
Этот совет Java иллюстрирует метод создания файлов ZIP. ZIP является универсальным форматом, используемым многими приложениями для сжатия своих файлов. Используя эту опцию, разработчик может дать свои пользовательские опции сжатия свои файлы в формате ZIP.
// These are the files to include in the ZIP file
String[] source = new String[]{"source1", "source2"};
// Create a buffer for reading the files
byte[] buf = new byte[1024];
try {
// Create the ZIP file
String target = "target.zip";
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target));
// Compress the files
for (int i=0; i<source.length; i++) {
FileInputStream in = new FileInputStream(source[i]);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(source[i]));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
} catch (IOException e) {
}
|
|
|
Этот совет Java иллюстрирует метод сжатия файла в формате GZIP. Gunzip это универсальный формат, используемый многими приложениями для сжатия своих файлов.
try {
// Create the GZIP output stream
String outFilename = "outfile.gzip";
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFilename));
// Open the input file
String inFilename = "infilename";
FileInputStream in = new FileInputStream(inFilename);
// Transfer bytes from the input file to the GZIP output stream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
// Complete the GZIP file
out.finish();
out.close();
} catch (IOException e) {
}
|
|
|
Этот совет Java иллюстрирует метод сжатия файла в формате GZIP. Gunzip это универсальный формат, используемый многими приложениями для сжатия своих файлов.
try {
// Create the GZIP output stream
String outFilename = "outfile.gzip";
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFilename));
// Open the input file
String inFilename = "infilename";
FileInputStream in = new FileInputStream(inFilename);
// Transfer bytes from the input file to the GZIP output stream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
// Complete the GZIP file
out.finish();
out.close();
} catch (IOException e) {
}
|
|
|
java.util.zip пакет предоставляет средства для создания Zip файлов.
В примере ниже создается Zip файл из нормального текстового файла:
import java.io.*;
import java.util.zip.*;
class makeZipFile {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println(
"Usage: java makeZipFile [files to be zipped] [filename after zip] ");
return;
}
try {
String filename = args[0];
String zipfilename = args[1];
makeZipFile list = new makeZipFile( );
list.doZip(filename,zipfilename);
} catch (Exception e) {
e.printStackTrace();
}
}
public void doZip(String filename,String zipfilename) {
try {
byte[] buf = new byte[1024];
FileInputStream fis = new FileInputStream(filename);
fis.read(buf,0,buf.length);
CRC32 crc = new CRC32();
ZipOutputStream s = new ZipOutputStream(
(OutputStream)new FileOutputStream(zipfilename));
s.setLevel(6);
ZipEntry entry = new ZipEntry(filename);
entry.setSize((long)buf.length);
crc.reset();
crc.update(buf);
entry.setCrc( crc.getValue());
s.putNextEntry(entry);
s.write(buf, 0, buf.length);
s.finish();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
|
|
Этот совет Java иллюстрирует метод перечисления содержимого файлов ZIP. Разработчик может использовать это как функциональность для своих пользователей, чтобы сначала увидеть содержимое файла ZIP, а затем распаковать выбранный.
try {
// Open the ZIP file
ZipFile sourcefile = new ZipFile("source.zip");
// Enumerate each entry
for (Enumeration entries = sourcefile.entries(); entries.hasMoreElements();) {
// Get the entry name
String zipEntryName = ((ZipEntry)entries.nextElement()).getName();
}
} catch (IOException e) {
}
|
|
|
Этот совет Java иллюстрирует метод перечисления содержимого файлов ZIP. Разработчик может использовать это как функциональность для своих пользователей, чтобы сначала увидеть содержимое файла ZIP, а затем распаковать выбранный.
try {
// Open the ZIP file
ZipFile sourcefile = new ZipFile("source.zip");
// Enumerate each entry
for (Enumeration entries = sourcefile.entries(); entries.hasMoreElements();) {
// Get the entry name
String zipEntryName = ((ZipEntry)entries.nextElement()).getName();
}
} catch (IOException e) {
}
|
|
|
Этот совет Java иллюстрирует метод распаковки файлов в формате GZIP. Gunzip это универсальный формат, используемый многими приложениями для сжатия своих файлов.
try {
// Open the compressed file
String source = "sourcename.gzip";
GZIPInputStream in = new GZIPInputStream(new FileInputStream(source));
// Open the output file
String target = "outfile";
OutputStream out = new FileOutputStream(target);
// Transfer bytes from the compressed file to the output file
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Close the file and stream
in.close();
out.close();
} catch (IOException e) {
}
|
|
|
Этот совет Java иллюстрирует метод распаковки файлов в формате GZIP. Gunzip это универсальный формат, используемый многими приложениями для сжатия своих файлов.
try {
// Open the compressed file
String source = "sourcename.gzip";
GZIPInputStream in = new GZIPInputStream(new FileInputStream(source));
// Open the output file
String target = "outfile";
OutputStream out = new FileOutputStream(target);
// Transfer bytes from the compressed file to the output file
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Close the file and stream
in.close();
out.close();
} catch (IOException e) {
}
|
|
|
java.util.zip предоставляет классы для извлечения, читать и писать Zip файлов.
Example below extracts files from given zip file into destination folder.
import java.io.*;
import java.util.zip.*;
class testZipFiles
{
public static void main(String[] args)
{
if (args.length != 1)
{
System.out.println("Usage: java testFiles [zipfile path] ");
return;
}
try
{
String filename = args[0];
testZipFiles list = new testZipFiles( );
list.getZipFiles(filename);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void getZipFiles(String filename)
{
try
{
String destinationname = "d:\\servlet\\testZip\\";
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(
new FileInputStream(filename));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null)
{
//for each entry to be extracted
String entryName = zipentry.getName();
System.out.println("entryname "+entryName);
int n;
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
String directory = newFile.getParent();
if(directory == null)
{
if(newFile.isDirectory())
break;
}
fileoutputstream = new FileOutputStream(
destinationname+entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1)
fileoutputstream.write(buf, 0, n);
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}//while
zipinputstream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
Example below extracts files from given zip file into destination folder.
import java.io.*;
import java.util.zip.*;
class testZipFiles
{
public static void main(String[] args)
{
if (args.length != 1)
{
System.out.println("Usage: java testFiles [zipfile path] ");
return;
}
try
{
String filename = args[0];
testZipFiles list = new testZipFiles( );
list.getZipFiles(filename);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void getZipFiles(String filename)
{
try
{
String destinationname = "d:\\servlet\\testZip\\";
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(
new FileInputStream(filename));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null)
{
//for each entry to be extracted
String entryName = zipentry.getName();
System.out.println("entryname "+entryName);
int n;
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
String directory = newFile.getParent();
if(directory == null)
{
if(newFile.isDirectory())
break;
}
fileoutputstream = new FileOutputStream(
destinationname+entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1)
fileoutputstream.write(buf, 0, n);
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}//while
zipinputstream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
import java.io.*;
import java.util.zip.*;
class testZipFiles
{
public static void main(String[] args)
{
if (args.length != 1)
{
System.out.println("Usage: java testFiles [zipfile path] ");
return;
}
try
{
String filename = args[0];
testZipFiles list = new testZipFiles( );
list.getZipFiles(filename);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void getZipFiles(String filename)
{
try
{
String destinationname = "d:\\servlet\\testZip\\";
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(
new FileInputStream(filename));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null)
{
//for each entry to be extracted
String entryName = zipentry.getName();
System.out.println("entryname "+entryName);
int n;
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
String directory = newFile.getParent();
if(directory == null)
{
if(newFile.isDirectory())
break;
}
fileoutputstream = new FileOutputStream(
destinationname+entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1)
fileoutputstream.write(buf, 0, n);
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}//while
zipinputstream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
|