Java access files in jar causes java.nio.file.FileSystemNotFoundException

你说的曾经没有我的故事 提交于 2019-11-29 20:35:32

A FileSystemNotFoundException means the file system cannot be created automatically; and you have not created it here.

Given your URI, what you should do is split against the !, open the filesystem using the part before it and then get the path from the part after the !:

final Map<String, String> env = new HashMap<>();
final String[] array = uri.toString().split("!");
final FileSystem fs = FileSystems.newFileSystem(URI.create(array[0]), env);
final Path path = fs.getPath(array[1]);

Note that you should .close() your FileSystem once you're done with it.

This is maybe a hack, but the following worked for me:

URI uri = getClass().getResource("myresourcefile.txt").toURI();

if("jar".equals(uri.getScheme())){
    for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
        if (provider.getScheme().equalsIgnoreCase("jar")) {
            try {
                provider.getFileSystem(uri);
            } catch (FileSystemNotFoundException e) {
                // in this case we need to initialize it first:
                provider.newFileSystem(uri, Collections.emptyMap());
            }
        }
    }
}
Path source = Paths.get(uri);

This uses the fact that ZipFileSystemProvider internally stores a List of FileSystems that were opened by URI.

Kinmarui

Accepted answer isn't the best since it doesn't work when you start application in IDE or resource is static and stored in classes! Better solution was proposed at java.nio.file.FileSystemNotFoundException when getting file from resources folder

InputStream in = getClass().getResourceAsStream("/webViewPresentation");
byte[] data = IOUtils.toByteArray(in);

IOUtils is from Apache commons-io.

But if you are already using Spring and want a text file you can change the second line to

StreamUtils.copyToString(in, Charset.defaultCharset());

StreamUtils.copyToByteArray also exists.

If you're using spring framework library, then there is an easy solution for it.

As per requirement we want to read webViewPresentation; I could solve the same problem with below code:

URI uri = getClass().getResource("/webViewPresentation").toURI();
FileSystems.getDefault().getPath(new UrlResource(uri).toString());
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!