java压缩文件

来源:互联网 发布:滴定度的浓度算法 编辑:程序博客网 时间:2024/06/05 11:26
public static void zipFileList(List<File> files , File destZipFile) {ZipOutputStream out = null;  FileInputStream in = null;try {out = new ZipOutputStream(new FileOutputStream(destZipFile)); for(File file:files) {byte[] buf = new byte[10240];      in = new FileInputStream(file);     out.putNextEntry(new ZipEntry(file.getName()));      int len;    while ((len = in.read(buf)) > 0) {                  out.write(buf, 0, len);              }                }}catch(Exception e) {e.printStackTrace();  }finally { try {                  if (out != null) {                out.close();                 }                  if (in != null)                      in.close();            } catch (IOException e) {              e.printStackTrace();              }}}

此方法传入一个文件列表和最终压缩的输出文件,适用于压缩一个或多个文件,可以在一个文件夹也可以不在一个文件夹,压缩之后的所有文件没有层级目录在一个文件夹内。

测试用例:

public static void main(String args[]) {System.out.println(System.currentTimeMillis());List<File> files = new ArrayList<>();files.add(new File("D:\\logs\\1.log"));files.add(new File("D:\\logs\\2.log"));files.add(new File("D:\\logs\\3.log"));files.add(new File("D:\\logs\\4.log"));files.add(new File("D:\\logs\\5.log"));files.add(new File("D:\\logs\\6.log"));;long startTime = System.currentTimeMillis();System.out.println(startTime);ZipUtil.zipFileList(files, new File("d:\\test.zip"));long endTime = System.currentTimeMillis();System.out.println(endTime);System.out.println(endTime - startTime);}

压缩消耗的时间与文件的多少关系不大,与文件的大小关系比较大

原创粉丝点击