通过Java复制Zip文件的最佳方法 [英] Best Way to copy a Zip File via Java
问题描述
经过一些研究:
和一些谷歌研究我想出了这个java函数:
and some google research i came up with this java function:
static void copyFile(File zipFile, File newFile) throws IOException {
ZipFile zipSrc = new ZipFile(zipFile);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(newFile));
Enumeration srcEntries = zipSrc.entries();
while (srcEntries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) srcEntries.nextElement();
ZipEntry newEntry = new ZipEntry(entry.getName());
zos.putNextEntry(newEntry);
BufferedInputStream bis = new BufferedInputStream(zipSrc
.getInputStream(entry));
while (bis.available() > 0) {
zos.write(bis.read());
}
zos.closeEntry();
bis.close();
}
zos.finish();
zos.close();
zipSrc.close();
}
此代码正常运行...但它并不干净整洁......任何人都有一个好主意或一个例子?
This code is working...but it is not nice and clean at all...anyone got a nice idea or an example?
编辑:
如果zip存档得到正确的结构,我希望能够添加某种类型的验证...因此将其复制为普通文件而不考虑其内容对我不起作用......或者您希望之后检查它... .i我不确定这个
I want to able to add some type of validation if the zip archive got the right structure...so copying it like an normal file without regarding its content is not working for me...or would you prefer checking it afterwards...i am not sure about this one
推荐答案
您只想复制完整的zip文件?打开并阅读zip文件不需要...只需将其复制就像复制其他文件一样。
You just want to copy the complete zip file? Than it is not needed to open and read the zip file... Just copy it like you would copy every other file.
public final static int BUF_SIZE = 1024; //can be much bigger, see comment below
public static void copyFile(File in, File out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
try {
byte[] buf = new byte[BUF_SIZE];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
throw e;
}
finally {
if (fis != null) fis.close();
if (fos != null) fos.close();
}
}
这篇关于通过Java复制Zip文件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!