Simple Java program:
public static String loadText(String file) {
StringBuilder finalString = new StringBuilder();
InputStream in = null;
BufferedReader reader = null;
InputStreamReader isr = null;
try{
System.out.println("Text File: " + file);
// Version 1
//URL url = Thread.currentThread().getClass().getResource(file);
//in = url.openStream();
// Version 2
in = Class.class.getResourceAsStream(file);
isr = new InputStreamReader(in);
reader = new BufferedReader(isr);
String line;
while((line = reader.readLine()) != null) {
finalString.append(line).append("//\n");
}
}
catch(IOException e) {
e.printStackTrace();
System.exit(-1);
}
finally {
try {
if (isr != null) { isr.close(); }
if (reader != null) { reader.close(); }
if (in != null) { in.close(); }
} catch (IOException e) { e.printStackTrace(); }
}
return finalString.toString();
}
The getResource
and getResourceAsStream
methods works fine in JDK 8 (java-8-openjdk-amd64) but they always return null
in JDK 11.
Questions: Why? And how can I fix this?
The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java. net.
You should always close streams (and any other Closeable, actually), no matter how they were given to you. Note that since Java 7, the preferred method to handle closing any resource is definitely the try-with-resources construct.
getResourceAsStream , send the absolute path from package root, but omitting the first / . If you use Class. getResourceAsStream , send either a path relative the the current Class object (and the method will take the package into account), or send the absolute path from package root, starting with a / .
The getResourceAsStream() method of java. lang. Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of InputStream object.
There is another solution using ClassLoader
ClassLoader.getSystemResourceAsStream(file)
loads from all locations. I'm using it to load resources from JAR file which holds just resources and no executable code so the previous trick can't work because there is no SomeClass
in the JAR to do SomeClass.class.getResourceAsStream()
I just don't understand the internals and I must change also the path of the file.
I have JAR file with file "my-file.txt" in the root of the JAR archive.
For java 8, this worked
Class.class.getResourceAsStream("/my-file.txt");
For java 11, I must remove the leading /
even when the file is in the root path
ClassLoader.getSystemResourceAsStream("my-file.txt");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With