簡體   English   中英

Java如何將zip文件轉換為帶有文件夾和文件的常規java.io.File

[英]Java how to turn zip file into regular java.io.File with folders and files

我正在研究將壓縮文件轉換為常規 java.io.File 的方法,其中所有文件和文件夾的順序與 zip 中的順序相同。 基本上我只想解壓縮壓縮文件而不將其內容復制到新目的地。 我已經提出了這個功能,到目前為止效果很好,但前提是 zip 中沒有文件夾。 zip 中的文件不能是目錄,否則我的功能將無法工作,這就是問題所在。
這是我的功能:

File unzip(File zip) throws IOException
    {
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zip));
        
        //helper directory to store files into while program is running!
        File helperDir = Files.createDirectories(Paths.get("zipFile")).toFile();  
        //helperDir.deleteOnExit();
        
        byte[] buffer = new byte[1024];
        for (ZipEntry entry; (entry = zis.getNextEntry()) != null; )
        {
            if (!entry.isDirectory()) //true if file in zip is not a folder
            {
                File newFile = new File(helperDir, entry.getName());
                //newFile.deleteOnExit();
                
                FileOutputStream fos = new FileOutputStream(newFile);
                for (int len = zis.read(buffer); len > 0; len = zis.read(buffer))
                    fos.write(buffer, 0, len);
                fos.close();
            }
            else
            {
                //What to do if there are folders in zip...
            }
        }
        
        zis.close();
        return helperDir;
    }

如何處理 zip 中的文件夾? 或者,是否有比如何更好的方法將 zip 轉換為 java.io.File?
請幫忙!

找到目錄后,您只需要多做一點就可以設置目錄。 要么在文件復制之前使用一行newFile.mkdirs()創建所需的目錄,要么在entry.isDirectory()時在 else 中創建目錄結構:

//What to do if there are folders in zip...
System.out.println("Reading dir  "+entry.getName());
File newDir = new File(helperDir, entry.getName());
newDir.mkdirs();

上面 3 行更好,因為它重現了空目錄,而僅添加newFile.mkdirs()只會創建其中包含文件的目錄。

Java NIO 提供了一個很好的方式來做同樣的解壓操作,下面是一個例子:

public static void unzip(Path zip, Path dir) throws IOException {
    try (FileSystem fs = FileSystems.newFileSystem(zip)) {
        for (Path root : fs.getRootDirectories()) {
            BiPredicate<Path, BasicFileAttributes> foreach = (p,a) -> {
                copy(p,a, Path.of(dir.toString(), p.toString()));
                return false;
            };
            Files.find(root, Integer.MAX_VALUE, foreach).count();
        }
    }
    System.out.println("UNZIPPED "+zip +" to "+dir);
}
private static void copy(Path from, BasicFileAttributes a, Path target)  {
    System.out.println("Copy "+(a.isDirectory() ? "DIR " : "FILE")+" => "+target);
    try {
        if (a.isDirectory())
            Files.createDirectories(target);
        else if (a.isRegularFile())
            Files.copy(from, target, StandardCopyOption.REPLACE_EXISTING);
    }
    catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM