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();
}
}
网友评论