使用java.util.zip包实现文件压缩
ZipOutputStream
public ZipOutputStream(OutputStream out)
构造函数,创建zip输出流public void putNextEntry(ZipEntry e)
设置每一个ZipEntry对象,即设置压缩元素名称(文件名)public void setComment(String comment)
设置文件注释public void write(byte b[])
写入zip文件内容
Example 1 压缩单文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author: dkangel
* @since: 2019/11/21 21:04
* @Description: 压缩单个文件
*/
public class ZipSingleFile {
public static void main(String[] args) throws Exception {
// 原始文件
String sourcePath = "D:/zip_test/test.txt";
File sourceFile = new File(sourcePath);
// zip文件名(包含文件路径)
String targetPath = "D:/zip_test/test.zip";
File targetFile = new File(targetPath);
// 原始文件数据读入流
InputStream input = new FileInputStream(sourceFile);
// zip文件输出流
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(targetFile));
// 定义压缩文件内容文件名
String contentFileName = "content.docx";
zipOut.putNextEntry(new ZipEntry(contentFileName));
zipOut.setComment("hello world.");
// 写入数据
int temp;
while ((temp = input.read()) != -1) {
zipOut.write(temp);
}
input.close();
zipOut.close();
}
}
测试结果:
压缩前:
压缩后:
结论:压缩单文件成功,压缩后文件内容不变,可以自定义zip文件名、内容文件名等。
Example 2 压缩文件夹(多文件压缩)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author: dkangel
* @since: 2019/11/21 21:32
* @Description:
*/
public class ZipMultipleFile {
public static void main(String[] args) throws IOException {
// 需要压缩文件夹路径
String sourcePath = "D:/zip_test/tmp";
File sourceFile = new File(sourcePath);
// zip文件输出路径
String targetPath = "D:/zip_test/zip_test.zip";
File targetFile = new File(targetPath);
// 定义zip输出流,用于将输入流内容写入zip文件
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(targetFile));
// 压缩文件
zipFile(sourceFile, zipOut);
zipOut.close();
}
/**
* 压缩文件
*
* @param sourceFile 原始文件
* @param zipOutputStream 压缩流
* @throws IOException
*/
private static void zipFile(File sourceFile, ZipOutputStream zipOutputStream) throws IOException {
// 文件夹,则递归遍历
if (sourceFile.isDirectory()) {
File[] files = sourceFile.listFiles();
if (files == null) {
return;
}
for (File subFile : files) {
zipFile(subFile, zipOutputStream);
}
}
// 文件,写入文件
if (sourceFile.isFile()) {
// 获取父路径
String regx = "tmp";
int index = sourceFile.getPath().indexOf(regx);
String fileName = sourceFile.getPath().substring(index + regx.length() + 1);
zipOutputStream.putNextEntry(new ZipEntry(fileName));
// 写入数据
int temp;
InputStream inputStream = new FileInputStream(sourceFile);
while ((temp = inputStream.read()) != -1) {
zipOutputStream.write(temp);
}
inputStream.close();
}
}
}
测试结果:
压缩前:
压缩后:
结论:文件夹压缩成功,压缩后文件内容不变,可以自定义zip文件名、内容文件名等。