Java zip打包工具类
先了解一下知识点:java.util.zipZipOutputStream:继承DeflaterOutputStream,该类实现了以ZIP文件格式写入文件的输出流过滤器。 包括对压缩和未压缩条目的支持。ZipEntry:此类用于表示ZIP文件条目。APIpublic void putNextEntry(ZipEntry e) :开始编写新的ZIP文件条目,并将流定位到条目数据的开...
·
先了解一下知识点:
java.util.zip
- ZipOutputStream:继承DeflaterOutputStream,该类实现了以ZIP文件格式写入文件的输出流过滤器。 包括对压缩和未压缩条目的支持。
- ZipEntry:此类用于表示ZIP文件条目。
API
- public void putNextEntry(ZipEntry e) :开始编写新的ZIP文件条目,并将流定位到条目数据的开头。
- public void write(int b) throws IOException:将一个字节写入压缩输出流。 此方法将阻塞,直到可以写入字节。
代码:
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* zip util
* @author rocky
* @date 2018-10-09 20:00
*/
public class ZipUtil {
/**
* 压缩目录下的文件
* @param filePath 要压缩的目录路径
* @param zipPath 生成的压缩包存放路径
* @throws FileNotFoundException
*/
public static void zipMutilFile(String filePath, String zipPath) throws FileNotFoundException {
File file = new File(filePath);
if (!file.isDirectory()) {
throw new FileNotFoundException("This file is not a directory.");
}
File zipFile = new File(zipPath);
InputStream inputStream = null;
try {
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
File[] files = file.listFiles();
for (File file1 : files) {
inputStream = new FileInputStream(file1);
zipOutputStream.putNextEntry(new ZipEntry(file.getName() + File.separator + file1.getName()));
int temp = 0;
while ((temp = inputStream.read()) != -1) {
zipOutputStream.write(temp);
}
inputStream.close();
}
zipOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)