简体   繁体   English

java zip 文件系统读取 zip 条目

[英]java zip filesystem reading zip entries

SO, from what I've gathered, one is supposed to be able to create a filesystem from a zip from java 7 and beyond.因此,据我收集的信息,应该能够从 java 7 及更高版本的 zip 创建文件系统。 I'm trying this, the ultimate goal is to use the File object and access these files, just as if I accessed an unzipped file.我正在尝试这个,最终目标是使用文件 object 并访问这些文件,就像我访问解压缩文件一样。

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class MainZipTest {

public static void main(String[] args) throws IOException, URISyntaxException {

    Map<String, String> env = new HashMap<>();
    env.put("read", "true");

    File file = new File("C:/pathtoazip/data.zip");
    URI uri = file.toURI();
    String path = "jar:" + uri;
    FileSystem fs = FileSystems.newFileSystem(URI.create(path), env);

    for (Path p : fs.getRootDirectories()) {
        System.out.println("root" + p);
        //says "/"
        System.out.println(new File(p.toString()).exists());
        for (File f : new File(p.toString()).listFiles())
            System.out.println(f.getAbsolutePath());
        //lists the contents of my c drive!
    }
    
    System.out.println(new File("somefile.txt").exists());
    System.out.println(fs.getPath("somefile.txt").toFile().exists());
    System.out.println(new File("/somefile.txt").exists());
    System.out.println(fs.getPath("/somefile.txt").toFile().exists());
}
}

it all prints "false".这一切都打印“假”。 What am I doing wrong here?我在这里做错了什么? Or am I wrong in my assumption that I can access these files through the File object?还是我假设我可以通过文件 object 访问这些文件是错误的? If so, how does one access them?如果是这样,如何访问它们?

Path was introduced as generalization of File (disk file). Path是作为File (磁盘文件)的泛化引入的。 A Path can be inside a zip file, an URL, and more.路径可以位于 zip 文件、URL 等文件中。

You can use Files with Path for similar File functionality.您可以使用带PathFiles来实现类似的文件功能。

for (Path p : fs.getRootDirectories()) {
    System.out.println("root: " + p);
    System.out.println(Files.exists(p));
    Files.list(p).forEach(f -> System.out.println(f.toAbsolutePath()));
}

Note that a Path, like from a zip will maintain its actual file system view (fs, the zip).请注意,路径,例如来自 zip 的路径将保持其实际的文件系统视图(fs,zip)。

So avoid File.所以避免文件。

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

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