java - 使用 FileSystems.newFileSystem(URI uri, Map<String, ?> env) 时出错

标签 java io path uri nio

我正在使用以下代码:

private static FileSystem createZipFileSystem(String zipFileName, boolean create) throws IOException {
    final Path path = Paths.get(zipFileName);
    final URI uri = URI.create("file:" + path.toUri().getPath());
    final Map<String,String> env = new HashMap<String,String>();

    if(create) {
        env.put("create", "true");
    }

    return FileSystems.newFileSystem(uri, env);
}

当我调用它时(dest是我项目中的一个文件夹):

createZipFileSystem("dest", true);

我收到以下错误:

Exception in thread "main" java.lang.IllegalArgumentException: Path component should be '/'
at sun.nio.fs.UnixFileSystemProvider.checkUri(UnixFileSystemProvider.java:77)
at sun.nio.fs.UnixFileSystemProvider.newFileSystem(UnixFileSystemProvider.java:86)
at java.nio.file.FileSystems.newFileSystem(FileSystems.java:326)
at java.nio.file.FileSystems.newFileSystem(FileSystems.java:276)
at com.jerney.ziptest.utils.ZipNIO.createZipFileSystem(ZipNIO.java:19)
at com.jerney.ziptest.utils.ZipNIO.getFileSystem(ZipNIO.java:23)
at com.jerney.ziptest.App.main(App.java:15)

我试过为 URI.create() 方法使用“jar:file:”、“file:/”和“file://”,并且我试过在末尾添加一个“/” “dest”,但我每次都得到相同的结果。我在 SO 上看到了另一个解决方案,建议使用不同的 FileSystems 工厂方法,但我特别想使用这个构造函数,并且知道为什么这对我不起作用。

最佳答案

每个 FileSystemProvider 都有自己的 URI 前缀。如果您使用 file: 前缀,您实际上是在请求默认的 FileSystemProvider(取决于您的机器或者 sun.nio.fs.UnixFileSystemProvider 的实例> 或 sun.nio.fs.WindowsFileSystemProvider)。

如果你想使用 ZipFileSystemProvider,你需要一个 jar: 前缀:

private static FileSystem createZipFileSystem(String zipFileName, boolean create) throws IOException {
    final Path path = Paths.get(zipFileName);
    final URI uri = URI.create("jar:" + path.toUri());
    final Map<String,String> env = new HashMap<String,String>();

    if(create) {
        env.put("create", "true");
    }

    return FileSystems.newFileSystem(uri, env);
}

关于java - 使用 FileSystems.newFileSystem(URI uri, Map<String, ?> env) 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43530119/

相关文章:

java - 写入包含子文件夹的新文件时自动创建完整路径

java - 拦截MainActivity中Fragment Dialog的Ok按钮点击

java - 带 JNA 的 x264 编码器

QT 使用共享访问打开文件

function - Elixir 检查是否从 ExUnit 测试中调用了一个函数?

python - 如何使用python在Elastic Search中索引路径/树?

Java 平面文件解析器 (jffp) LineFormatTest

java - 将 PEM 证书解析为 JSON

不可序列化第三方类的Java序列化

windows - 如何在 Cygwin 命令行上将 Windows 路径格式化为 Unix 路径