JAVA把指定文件放入压缩包
作者:互联网
/**
* 测试多个文件放入压缩包
* @param args
*/
public static void main(String[] args) {
Map<String, File> srcfile = new HashMap<String, File>(){{
//key为压缩后的名称(随便起), value为被压缩的文件的全路径
put("1.pdf", new File("D:\\wenjian\\test\\test.pdf"));
put("2.xls", new File("D:\\wenjian\\test\\test1.xls"));
}};
//压缩后存储的全路径
String url = "D:\\wenjian\\test\\cs\\"+ "abc.zip";
zipFiles(srcfile, new File(url));
}
public static void zipFiles(Map<String, File> srcfile, File zipfile) {
byte[] buf = new byte[10240];
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile))) {
srcfile.forEach((key, value) -> {
try {
try (FileInputStream in = new FileInputStream(value)) {
out.putNextEntry(new ZipEntry(key));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
执行结果:
打开压缩包后是刚刚放进去的两个文件 ↓
标签:JAVA,srcfile,test,File,catch,new,放入,压缩包,out 来源: https://blog.csdn.net/weixin_42915457/article/details/114928539