从资源文件夹获取文件时,java.nio.file.FileSystemNotFoundException [英] java.nio.file.FileSystemNotFoundException when getting file from resources folder
问题描述
我在以下代码上遇到此错误(请注意,这不会在本地计算机上发生,仅在我的构建服务器上发生):
I am getting this error on the following code (note that this does not happen on my local machine, only on my build server):
Files.readAllBytes(Paths.get(getClass().getResource("/elasticsearch/segmentsIndex.json").toURI()), Charset.defaultCharset());
还有一个例外:
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)
我试图通过遵循以下解决方案来解决此问题;我的代码现在看起来像这样:
I tried to fix it by following this solution; my code now looks like this:
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)
似乎没有任何作用. 我应该如何建立文件的路径?
Nothing seems to work. How am I supposed to build the path to the file?
推荐答案
不要尝试访问文件之类的资源.只需抓住InputStream并从那里读取数据:
Don't try to access a resource like a file. Just grab the InputStream and read the data from there:
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类.
This example uses the IOUtils class from Apache commons-io library.
如果您的目标是Java 9+,则可以选择使用data = in.readAllBytes();
.
If you are targeting Java 9+ you can alternatively use data = in.readAllBytes();
.
这篇关于从资源文件夹获取文件时,java.nio.file.FileSystemNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!