从资源文件夹获取文件时出现 java.nio.file.FileSystemNotFoundException

标签 java nio

我在以下代码中遇到此错误(请注意,这不会发生在我的本地机器上,只会发生在我的构建服务器上):

Files.readAllBytes(Paths.get(getClass().getResource("/elasticsearch/segmentsIndex.json").toURI()), Charset.defaultCharset());

异常(exception)情况:

Caused by: java.nio.file.FileSystemNotFoundException: null
at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171)
at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
at java.nio.file.Paths.get(Paths.java:143)

我尝试按照此 solution 修复它;我的代码现在看起来像这样:

URI segmentsIndexURI = getClass().getResource("/elasticsearch/segmentsIndex.json").toURI();
Map<String, String> env = new HashMap<>(); 
env.put("create", "true");
FileSystem zipfs = FileSystems.newFileSystem(segmentsIndexURI, env); //exception here
Path segmentsIndexPath = Paths.get(segmentsIndexURI);

我收到以下异常:

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)

似乎没有任何效果。 我应该如何构建文件的路径?

最佳答案

不要尝试访问文件之类的资源。只需获取 InputStream 并从那里读取数据:

byte[] data;
try (InputStream in = getClass().getResourceAsStream("/elasticsearch/segmentsIndex.json")) {
    data = in.readAllBytes​(); // usable in Java 9+
    // data = IOUtils.toByteArray(in); // uses Apache commons IO library
}

此示例使用 Apache commons-io 库中的 IOUtils 类。

如果您的目标是 Java 9+,您也可以使用 data = in.readAllBytes ();

关于从资源文件夹获取文件时出现 java.nio.file.FileSystemNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29746667/

相关文章:

java - 为什么我的哈希值在 Java 中永远不匹配?

java - 使用 Java NIO 获取文件创建日期

特定文件系统的 Java 路径

java - 是否可以在运行时复制所有资源文件(无需特别命名)?

Java 如何仅将 onTouchEvent 运动设置为某些对象

java - 如何通过鼠标按下和拖动关闭 jtable 单元格选择

scala - 在Scala中处理文件时出现java.nio.BufferUnderflowException

java - Java NIO 2 中的多线程模型 - (前摄器模式)是什么?

java - 如何明确方法的参数作为返回值?

java - Android 的替代 XML 解析器实现