java ZipEntry 到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36890005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:59:04  来源:igfitidea点击:

ZipEntry to File

javafilezip

提问by JF Meier

Is there a direct way to unpack a java.util.zip.ZipEntryto a File?

有没有直接的方法将 a 解包java.util.zip.ZipEntry到 a File

I want to specify a location (like "C:\temp\myfile.java") and unpack the Entry to that location.

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

There is some code with streams on the net, but I would prefer a tested library function.

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

回答by Evgeniy Dorofeev

Use ZipFile class

使用 ZipFile 类

    ZipFile zf = new ZipFile("zipfile");

Get entry

获取条目

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

Get inpustream

获取输入流

    InputStream is = zf.getInputStream(e);

Save bytes

节省字节

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

回答by Coffee Monkey

Use ZipInputStreamto move to the desired ZipEntryby iterating using the getNextEntry()method. Then use the ZipInputStream.read(...)method to read the bytes for the current ZipEntry. Output those bytes to a FileOutputStreampointing to a file of your choice.

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

回答by Shakthifuture

I have extractor the zip file into File and added it into the list using ZipEntry. Hopefully, this will help you.

我已将 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;
}