Reputation: 402
I used Class.getResource (String) to retrieve the url of a file, and it works very well, but when I try to 'insatncié a FileReader with the url returned, an exception:java.io.FileNotFoundException is triggered
URL bpmnResourceUrl = ConvertXmlToJson.class.getClassLoader().getResource("file.txt");
Reader reader = new FileReader(bpmnResourceUrl.toString());
Upvotes: 0
Views: 3390
Reputation: 9080
Don't open it as a file, use it as InputStream, in your case, if you want a Reader to get the data then you can use:
InputStream is = ConvertXmlToJson.class.getClassLoader().getResourceAsStream("file.txt");
Reader reader = new InputStreamReader(is);
When you load a resource from Classpath, such resource can be located inside a jar file, so It's not accesible like a regular file in filesystem, but you can open a Stream to read it, as the code shows.
Upvotes: 0
Reputation: 8068
A Resource in Java is not a File. If the Resource is inside a JAR, for example, you can't access it like a File. You have to explode the JAR first. You may try:
Class.getResourceAsStream()
to read the content. Here is a short example:
public class Example {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(Example.class.getResourceAsStream("/META-INF/MANIFEST.MF")));
String line;
do {
line = br.readLine();
if (line != null) System.out.println(line);
} while (line != null);
}
}
Upvotes: 4