I am trying to replace all instances of using Files and FileReaders and replace them with InputStreams and appropriate readers in preparation for packing the app in a jar - however, when I try to use ClassLoader.getSystemClassLoader().getResourceAsStream()
with the same path that the File approach managed to find, it fails due to failing to find the file.
The code I use and output:
The text in the file:
e:Easy
definitions/easy_level_definitions.txt
h:Hard
definitions/hard_level_definitions.txt
d:Derp
definitions/derp_level_definitions.txt
Code:
String line;
File f = new File("src/resources/level_sets.txt");
BufferedReader reader1 = null;
try {
reader1 = new BufferedReader(new FileReader(f));
while ((line = reader1.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader1 != null) {
reader1.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
line = null;
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("src/resources/level_sets.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Output:
e:Easy
definitions/easy_level_definitions.txt
h:Hard
definitions/hard_level_definitions.txt
d:Derp
definitions/derp_level_definitions.txt
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source)
at java.io.InputStreamReader.<init>(Unknown Source)
at Testing.main(Testing.java:34)
The "src" folder is only available in your IDE. Once the app is packaged, it wont exist anymore and the resource will be available at the root of the classpath. Use this: