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

Gle*_*eeb 7 java nio

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

Files.readAllBytes(Paths.get(getClass().getResource("/elasticsearch/segmentsIndex.json").toURI()), Charset.defaultCharset());
Run Code Online (Sandbox Code Playgroud)

例外情况:

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)
Run Code Online (Sandbox Code Playgroud)

我尝试通过遵循此解决方案来解决它; 我的代码现在看起来像这样:

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);
Run Code Online (Sandbox Code Playgroud)

我收到以下异常:

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)
Run Code Online (Sandbox Code Playgroud)

似乎没什么用.我该如何构建文件的路径?

Rob*_*ert 12

不要尝试访问像文件这样的资源.只需抓住InputStream并从那里读取数据:

byte[] data;
try (InputStream in = getClass().getResourceAsStream("/elasticsearch/segmentsIndex.json")) {
    data = IOUtils.toByteArray(in); // uses Apache commons IO library
    // data = in.readAllBytes?(); // alternative way, usable in Java 9+
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我必须添加 `getClass().getClassLoader()` (2认同)

bot*_*ius 5

通常,假设每个资源都是一个文件是不正确的。相反,您应该获取该资源的URL / InputStream并从那里读取字节。番石榴可以帮助:

URL url = getClass().getResource("/elasticsearch/segmentsIndex.json");
String content = Resources.toString(url, charset);
Run Code Online (Sandbox Code Playgroud)


另一种可能的解决方案是使用InputStream和apache公用:将InputStream转换为Java中的字节数组

从byte [],只需使用String构造函数即可将内容作为字符串获取。


归档时间:

查看次数:

10529 次

最近记录:

5 年,11 月 前