通过Java复制Zip文件的最佳方法

经过一番研究:

如何创建Zip文件

和一些谷歌研究我想出了这个java函数:

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(); } 

这段代码正在运行……但它并不好看和干净……任何人都有一个好主意或一个例子?

编辑:

我想能够添加一些类型的validation,如果zip存档得到正确的结构…所以复制它像普通文件而不考虑其内容对我不起作用…或者你更喜欢之后检查…我不确定这个

你只想复制完整的zip文件? 比不需要打开和读取zip文件…只需复制它就像复制其他文件一样。

 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(); } } 

尝试: http : //commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#copyFile Apache Commons FileUtils #copyFile

我的解决方案

 import java.io.*; import javax.swing.*; public class MovingFile { public static void copyStreamToFile() throws IOException { FileOutputStream foutOutput = null; String oldDir = "F:/UPLOADT.zip"; System.out.println(oldDir); String newDir = "F:/NewFolder/UPLOADT.zip"; // name as the destination file name to be done File f = new File(oldDir); f.renameTo(new File(newDir)); } public static void main(String[] args) throws IOException { copyStreamToFile(); } }