Java多文件压缩

public static void main(String[] args) {
//文件夹
File file = new File("C:/Users/Administrator/Desktop/javatest");
//文件输出流
try(OutputStream os = new FileOutputStream("d:/archive.zip");) {
//创建文件压缩流(处理流|过滤流)
ZipOutputStream zip = new ZipOutputStream(os);
//闯将文件输出缓冲流
BufferedOutputStream bos = new BufferedOutputStream(zip);
String[] fileNames = file.list();
for (String string : fileNames) {
//添加实体
zip.putNextEntry(new ZipEntry(string));
try(InputStream in = new FileInputStream(file.getAbsolutePath() + "/"+string)){
byte[] buffer = new byte[4096];
int len;
while((len = in.read(buffer)) != -1){
bos.write(buffer,0,len);
}
//带缓冲的流需要清空缓冲区,强行把缓冲区的数据写到数据流中
bos.flush();
}
//zip.closeEntry(); 可省略
}
zip.finish(); //必须做完
System.out.println("压缩完成!");
}catch (IOException e1) {
e1.printStackTrace();
}
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容