Apache Commons Compress 压缩zip

王楚青
2023-12-01

1.序言

官网提供了一个例子,研究了一天才知怎么用。

2.版本

Apache Commons Compress1.12

3.官网例子

public class ScatterSample {
	ParallelScatterZipCreator scatterZipCreator = new ParallelScatterZipCreator();
	ScatterZipOutputStream dirs = ScatterZipOutputStream.fileBased(File.createTempFile("scatter-dirs", "tmp"));

	public ScatterSample() throws IOException {
	}

	public void addEntry(ZipArchiveEntry zipArchiveEntry, InputStreamSupplier streamSupplier) throws IOException {
		if (zipArchiveEntry.isDirectory() && !zipArchiveEntry.isUnixSymlink())
			dirs.addArchiveEntry(ZipArchiveEntryRequest.createZipArchiveEntryRequest(zipArchiveEntry, streamSupplier));
		else
			scatterZipCreator.addArchiveEntry(zipArchiveEntry, streamSupplier);
	}

	public void writeTo(ZipArchiveOutputStream zipArchiveOutputStream)
			throws IOException, ExecutionException, InterruptedException {
		dirs.writeTo(zipArchiveOutputStream);
		dirs.close();
		scatterZipCreator.writeTo(zipArchiveOutputStream);
	}
}

4.调用方式

public class ZipInputStream implements InputStreamSupplier{

	@Override
	public InputStream get() {
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(new File("f:/write.docx"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return inputStream;
	}

}
		ScatterSample scatterSample = new ScatterSample();
		ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(new File("f:/test.zip"));
		ZipArchiveEntry entry = new ZipArchiveEntry("write.docx");
		entry.setMethod(ZipMethod.STORED.getCode());
		scatterSample.addEntry(entry, new ZipInputStream());
		scatterSample.writeTo(zipArchiveOutputStream);
		zipArchiveOutputStream.close();


5.说两句

这个是我的测试,要用的话,请自行整理出来,灵活调用,write.docx是我提前准备压缩进test.zip的文件,您需要事先准备该文件,test.zip是自动生成的,不用管。

 类似资料: