繁体   English   中英

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

[英]Best Way to copy a Zip File via Java

经过一番研究:

如何创建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();
 }

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

编辑:

我想能够添加一些类型的验证,如果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();
  }
}

我的解决方案

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM