java实现文件压缩

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFile {
public static void main(String[] args) {
ArrayList fileNames = new ArrayList(); // 存放文件名,并非含有路径的名字
ArrayList files = new ArrayList(); // 存放文件对象

try {
FileOutputStream fileOut = new FileOutputStream(
"E:/ZipOutOfPath.zip");
ZipOutputStream outputStream = new ZipOutputStream(fileOut);

File rootFile = new File("E:/temp");
listFile(rootFile, fileNames, files);
for (int loop = 0; loop < files.size(); loop++) {
FileInputStream fileIn = new FileInputStream((File) files
.get(loop));
outputStream.putNextEntry(new ZipEntry((String) fileNames
.get(loop)));
byte[] buffer = new byte[1024];
while (fileIn.read(buffer) != -1) {
outputStream.write(buffer);
}

outputStream.closeEntry();
fileIn.close();
}

outputStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

static void listFile(File parentFile, List nameList, List fileList) {
if (parentFile.isDirectory()) {
File[] files = parentFile.listFiles();
for (int loop = 0; loop < files.length; loop++) {
listFile(files[loop], nameList, fileList);
}
} else {
fileList.add(parentFile);
nameList.add(parentFile.getName());
}
}
}

你可能感兴趣的:(java)