我在以下代码中遇到此错误(请注意,这不会发生在我的本地机器上,只会发生在我的构建服务器上):
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/