本文共 1860 字,大约阅读时间需要 6 分钟。
使用java.util.zip包来生成压缩文件简单示例:
public static void main(String[] args) { try ( // 读取需要压缩的文件,也可从其他途径获取 FileInputStream fileInputStream1 = new FileInputStream("D://file/file-1.tsv"); FileInputStream fileInputStream2 = new FileInputStream("D://file/file-2.txt"); FileInputStream fileInputStream3 = new FileInputStream("D://file/file-3.xls"); // 定义压缩文件输出流,经测试,zip和rar格式均能正常生成 FileOutputStream fileOutputStream = new FileOutputStream("D://file/test.zip"); // 1、定义压缩输出流,数据放入后再输出,会进行压缩 ZipOutputStream zipOut = new ZipOutputStream(fileOutputStream) ) { FileInputStream[] fileInputStreams = { fileInputStream1, fileInputStream2, fileInputStream3}; // 压缩文件中的各个文件名 String[] fileNames = { "file-1.tsv", "file-2.tsv", "file-3.tsv"}; // 循环处理各个需要压缩的文件,不太清楚使用FileChannel读取数据,可以移步本人关于NIO的总结,其中有比较详细的介绍 // 传送 https://blog.csdn.net/D578332749/article/details/97390888 for (int i = 0; i < fileInputStreams.length; i++) { FileChannel fileChannel = fileInputStreams[i].getChannel(); ByteBuffer buf = ByteBuffer.allocate(128); int bytesRead = fileChannel.read(buf); // 2、放入一个文件实体,在此后直至下一次putNextEntry所有write的数据,均属于这个实体 zipOut.putNextEntry(new ZipEntry(fileNames[i])); while (bytesRead != -1) { buf.flip(); while (buf.hasRemaining()) { // 3、写入数据 zipOut.write(buf.get()); } buf.clear(); bytesRead = fileChannel.read(buf); } } // 4、结束压缩 zipOut.finish(); } catch (Exception e) { System.out.println(e); }}
简单总结,使用java.util.zip包来生成zip压缩文件主要有4个关键步骤: