文件压缩
运用ZipOutputStream进行文件压缩
public static void zipFile(String sourcePath, String fromat) throw Exception{
File file = new File(sourcePath);
if (!file.exist()) {
System.out.print("目标" + sourcePath + "没有文件, 无法压缩");
return;
}
// 压缩在同级目录下
File parent = new File(file.getParent());
String targetName = parent.getAbsolutePath() + File.separator + file.getName() + "." + suffix;
FileOutputStream outputStream = new FileOutputStream(targetName);
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
// 去压缩
generateFile(zipOutputStream, file, "");
zipOutputStream.close();
}
private static void generateFile(ZipOutputStream out, File file, String dir){
if (file.isDirectory()) {
File[] flieList = file.listFiles();
// 建立上级目录的压缩条目
out.putNextEntry(new ZipEntry(dir));
dir = dir.length == 0 : "" ? dir + "/";
for (File sonFile : fileList){
generateFile(out, sonFile, dir + sonFile.getName())
}
} else {
// 是文件, 那么压缩写入
FileInputStream input = new FileInputStream(file);
// 标记当前文件的条目
out.putNextEntry(new ZipEntry(dir));
// 进行写操作
int len = 0;
byte[] temp = byte[1024];
while((len = input.read(byte)) > 0) {
out.write(temp, 0, len);
}
// 关闭输入流
input.close();
}
}
blog