java.nio.file.FileSystemNotFoundException when getting file from resources folder

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
}

This example uses the IOUtils class from Apache commons-io library.

If you are targeting Java 9+ you can alternatively use data = in.readAllBytes​();.


Generally, it is not correct to assume that every resource is a file. Instead, you should obtain the URL/InputStream for that resource and read the bytes from there. Guava can help:

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


Another possible solution, with the InputStream and apache commons: Convert InputStream to byte array in Java .

From a byte[], simply use the String constructor to obtain the content as a string.


You should get the resource through an InputStream and not a File, but there is no need for external libraries.

All you need is a couple of lines of code:

InputStream is = getClass().getResourceAsStream("/elasticsearch/segmentsIndex.json");
java.util.Scanner scanner = new java.util.Scanner(is).useDelimiter("\\A");
String json = scanner.hasNext() ? scanner.next() : "";

You can learn more about that method at https://stackoverflow.com/a/5445161/968244

Tags:

Java

Nio