zipoutputstream设置名称_java:更改ZipEntry的名字

I have the following code that writes a text file in a zip:

FileOutputStream fOut = new FileOutputStream(fullFilename, false);

BufferedOutputStream bOut = new BufferedOutputStream(fOut);

ZipOutputStream zOut = new ZipOutputStream(bOut);

zOut.putNextEntry(new ZipEntry("aFile1.txt"));

//Do some processing and write to zOut...

zOut.write(...);

(...)

zOut.closeEntry();

zOut.close();

//Etc (close all resources)

I would need to change the filename of the zipEntry after it has been written (as its name will depend on its content written).

Also, it is not an option to write in a buffer and write to file only when final filename is known (because file size is potentially very large: not enough memory).

Any advice on how to do this would be greatly appreciated!

Thanks,

Thomas

解决方案

It is a missing functionality, which could have been simple, as the entries themselves are not compressed.

The easiest way, requiring a rewrite though, is the zip FileSystem: since java 7 you may use a zip file as a virtual file system: writing, renaming and moving files in them. An example. You copy a file from the normal file system into the zip file system, and later rename the file in the zip.

// Create the zip file:

URI zipURI = URI.create("jar:file:" + fullFilename); // "jar:file:/.../... .zip"

Map env = new HashMap<>();

env.put("create", "true");

FileSystem zipFS = FileSystems.newFileSystem(zipURI, env, null);

// Write to aFile1.txt:

Path pathInZipfile = zipFS.getPath("/aFile1.txt");

BufferedWriter out = Files.newBufferedWriter(pathInZipfile,

StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);

out.write("Press any key, except both shift keys\n");

out.close();

// Rename file:

Path pathInZipfile2 = zipFS.getPath("/aFile2.txt");

Files.move(pathInZipfile, pathInZipfile2);

zipFS.close();

In principle you could also keep your old code - without renaming. And use a zip file system just for renaming.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值