首先,对文件进行压缩
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) {
}
蓝色字体为要压缩的文件的位置及文件名,可以一个也可以多个,中间用“,”隔开,要注意的是文件名的扩展名也要写上。
红色字体是压缩后的文件位置及压缩包名,扩展名为zip
下面介绍如何解压缩
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) {
}
绿色字体位置添加要解压的文件位置及文件名(包括扩展名),这个是用来遍历压缩文件中的文件数的
黄色字体也添加要解压的文件位置及文件名(包括扩展名),这个是将压缩文件中的文件解压开。