读书人

JAVA对资料压缩和解压缩的实现

发布时间: 2012-11-06 14:07:00 作者: rapoo

JAVA对文件压缩和解压缩的实现
很实用的功能,JAVA对文件进行操作,压缩和解压缩

1.对文件进行压缩

String[] filenames =new String[]{"c:\\qqq.txt","c:\\www.txt"};
//new String[]{"c:\\aaa.txt", "c:\\bbb.java"};

byte[] buf = new byte[1024];

try {
String outFilename = "c:\\XXX.zip";
ZipOutputStream out =
new ZipOutputStream(new FileOutputStream(outFilename));

for (int i=0; i<filenames.length; i++) {
FileInputStream in = new FileInputStream(filenames[i]);

out.putNextEntry(new ZipEntry(filenames[i]));

int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}

out.closeEntry();
in.close();
}

out.close();
} catch (IOException e) {
}

2.下面介绍如何解压缩

try {
String inFilename = "c:\\XXX.zip");
ZipInputStream in =
new ZipInputStream(new FileInputStream(inFilename));


ZipFile zf = new ZipFile("c:\\XXX.zip");

for (Enumeration entries =
zf.entries(); entries.hasMoreElements();)
{
String zipEntryName =
((ZipEntry)entries.nextElement()).getName();

ZipEntry entry = in.getNextEntry();


String outFilename = zipEntryName;
OutputStream out = new FileOutputStream(outFilename);

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) {
}

读书人网 >编程

热点推荐