【问题标题】:ZipEntry to FileZipEntry 到文件
【发布时间】:2016-08-21 18:17:13
【问题描述】:

有没有直接的方法将java.util.zip.ZipEntry 解压为File

我想指定一个位置(如“C:\temp\myfile.java”)并将条目解压缩到该位置。

网上有一些带流的代码,但我更喜欢经过测试的库函数。

【问题讨论】:

  • "...to a File?" File 是路径名的抽象表示。你的意思是“文件”(没有代码标记)?
  • 意思是,我给函数一个文件,它解压到那个抽象路径名的入口。
  • 如果这不清楚或重复,我很抱歉,但请发表评论而不是仅仅投反对票。

标签: java file zip


【解决方案1】:

通过使用getNextEntry() 方法进行迭代,使用ZipInputStream 移动到所需的ZipEntry。然后使用ZipInputStream.read(...) 方法读取当前ZipEntry 的字节。将这些字节输出到指向您选择的文件的FileOutputStream

【讨论】:

  • 这意味着:不,没有库函数?
  • 是的,@JFMeier 是的,你说得对)有很多 Java 没有的库函数。
【解决方案2】:

使用 ZipFile 类

    ZipFile zf = new ZipFile("zipfile");

获取条目

    ZipEntry e = zf.getEntry("name");

获取输入流

    InputStream is = zf.getInputStream(e);

节省字节

    Files.copy(is, Paths.get("C:\\temp\\myfile.java"));

【讨论】:

    【解决方案3】:

    使用以下代码将“zip 文件”解压缩到 File 中,然后使用 ZipEntry 添加到列表中。希望这会对您有所帮助。

    private List<File> unzip(Resource resource) {
        List<File> files = new ArrayList<>();
        try {
            ZipInputStream zin = new ZipInputStream(resource.getInputStream());
            ZipEntry entry = null;
            while((entry = zin.getNextEntry()) != null) {
                File file = new File(entry.getName());
                FileOutputStream  os = new FileOutputStream(file);
                for (int c = zin.read(); c != -1; c = zin.read()) {
                    os.write(c);
                }
                os.close();
                files.add(file);
            }
        } catch (IOException e) {
            log.error("Error while extract the zip: "+e);
        }
        return files;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      相关资源
      最近更新 更多