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

时间:2009-12-22 13:10:40

标签: java zip

经过一些研究:

How to create a Zip File

和一些谷歌研究我想出了这个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();
 }

这段代码正在运行......但是它根本不是很干净......任何人都有一个好主意或一个例子?

修改

如果zip存档具有正确的结构,我希望能够添加某种类型的验证...因此将其复制为普通文件而不考虑其内容对我不起作用...或者您希望之后再检查它......我不确定这个

4 个答案:

答案 0 :(得分:10)

您只想复制完整的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();
  }
}

答案 1 :(得分:6)

答案 2 :(得分:0)

我的解决方案:

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

答案 3 :(得分:0)

我已将您的代码更新为 Java 9+,FWIW

   try (ZipFile srcFile = new ZipFile(inputName)) {
        try (ZipOutputStream destFile = new ZipOutputStream(
                Files.newOutputStream(Paths.get(new File(outputName).toURI())))) {
            Enumeration<? extends ZipEntry> entries = srcFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry src = entries.nextElement();
                ZipEntry dest = new ZipEntry(src.getName());
                destFile.putNextEntry(dest);
                try (InputStream content = srcFile.getInputStream(src)) {
                    content.transferTo(destFile);
                }
                destFile.closeEntry();
            }
            destFile.finish();
        }
    }