|
java.util.zip пакет предоставляет возможность чтения / записи Zip файлов.
Пример ниже показывает список файлов, содержащихся в Zip файл и читает первую строку файла.
import java.io.*;
import java.util.zip.*;
class readZipFiles
{
public static void main(String[] args)
{
if (args.length != 1)
{
System.out.println("Usage: java testFiles [zipfile path] ");
return;
}
try
{
String filename = args[0];
readZipFiles list = new readZipFiles( );
list.readZipFiles(filename);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void readZipFiles(String filename)
{
try
{
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("File ::"+entryName);
RandomAccessFile rf;
File newFile = new File(entryName);
String directory = newFile.getParent();
if(directory == null)
{
if(newFile.isDirectory())
break;
}
rf = new RandomAccessFile(entryName,"r");
String line;
if ((line =rf.readLine()) !=null)
{
System.out.println(line);
}
rf.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}//while
zipinputstream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
|
|
Этот образец кода показывает способ создания Zip-файлов и добавлять файлы в нее. Он использует ZipOutputStream писать Zip файл.
import
|
Этот совет Java иллюстрирует пример сжатия массив байтов. Разработчик может сжать массив байтов с помощью класса Deflater.
byte[] input = "compression string".getBytes();
// Compressor with highest level of compression
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
// Give the compressor the data to compress
compressor.setInput(input);
compressor.finish();
// Create an expandable byte array to hold the compressed data.
// It is not necessary that the compressed data will be smaller than
// the uncompressed data.
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
// Compress the data
byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
try {
bos.close();
} catch (IOException e) {
}
// Get the compressed data
byte[] compressedData = bos.toByteArray();
|
|
|
|
|
Этот совет Java приведен пример декомпрессии массив байтов. Разработчик может распаковывает байтовый массив, сжатые с помощью класса Deflater.
// Create the decompressor and give it the data to compress
Inflater decompressor = new Inflater();
decompressor.setInput(compressedData);
// Create an expandable byte array to hold the decompressed data
ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);
// Decompress the data
byte[] buf = new byte[1024];
while (!decompressor.finished()) {
try {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
} catch (DataFormatException e) {
}
}
try {
bos.close();
} catch (IOException e) {
}
// Get the decompressed data
byte[] decompressedData = bos.toByteArray();
|
|
|
Этот образец кода прочитать имя все файлы из архива:. Он использует ZipInputStream следующего файла Zip.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipFileRdrExp {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("C:\\MyZip.zip");
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze;
while((ze=zis.getNextEntry())!=null){
System.out.println(ze.getName());
zis.closeEntry();
}
zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
|
|
Этот совет 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) {
}
|
|