解压缩并重新压缩文件而不写入磁盘 - Java
问题描述:
我正在尝试编写一个程序来解压缩和重新压缩文件,而不用写入Java中的磁盘。到目前为止,我有,解压缩并重新压缩文件而不写入磁盘 - Java
public void unzipFile(String filePath) {
FileInputStream fis = null;
ZipInputStream zipIs = null;
ZipEntry zEntry = null;
try {
fis = new FileInputStream(filePath);
zipIs = new ZipInputStream(new BufferedInputStream(fis));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
while ((zEntry = zipIs.getNextEntry()) != null) {
zos.putNewEntry(zEntry);
zos.write(...);
zos.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
}
我的问题是我不知道如何编写到ZipOutputStream的ZipEntry。我收到错误,“java.util.zip.ZipException:无效的项目大小(预期125673,但得到0字节)”。任何人都可以将我指向正确的方向吗?
答
你只需要将数据从ZipInputStream
复制到ZipOutputStream
你有zos.write(...)
声明。下面,我已将该副本隔离到名为copyStream()
的帮助程序方法,但如果需要,可以将其内联。
此外,不要关闭循环内的流。我还更改了代码以使用try-with-resources,以便更好地管理资源,因此您再也看不到任何close()
调用。
这里是一个正在运行的例子:我的机器上
public static void main(String[] args) throws Exception {
String filePath = System.getProperty("java.home") + "/lib/rt.jar";
rezipFile(filePath);
}
public static void rezipFile(String filePath) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(filePath)));
ZipOutputStream zos = new ZipOutputStream(baos);
) {
for (ZipEntry zEntry; (zEntry = zis.getNextEntry()) != null;) {
zos.putNextEntry(zEntry);
copyStream(zis, zos);
}
}
System.out.println(baos.size() + " bytes copied");
}
private static void copyStream(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[4096];
for (int len; (len = in.read(buf)) > 0;)
out.write(buf, 0, len);
}
输出:
63275847 bytes copied
嗯,首先,不叫'close()方法'内循环。 – Andreas
你是怎么调用这个方法的? –
''好吧,对于初学者来说,不要在循环中调用close()。“ - 严重 –