通过 Java 复制和验证 Zip 文件 [英] Copy and validate a Zip File via Java

查看:32
本文介绍了通过 Java 复制和验证 Zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一些研究:

如何创建 Zip 文件

和一些谷歌研究我想出了这个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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆