Reputation: 1507
I am trying to read a file inside my jar from another class inside the jar. However I am continually getting the same error: Caught: class java.io.FileNotFoundException while attempting to read metrics: metrics.yml
At first I had my code do something like this, assuming it was from the path of the class:
String yamlPath = ".." + File.separator + ".." + File.separator + ".." + File.separator + ".." + File.separator + "myYaml.yml";
InputStream in = new FileInputStream(new File(yamlPath));
InputStreamReader isr = new InputStreamReader(in);
BufferedReader input = new BufferedReader(isr);
yamlObj = (HashMap) javaYAML.load(input);
I also did this assuming it might take the path from the base of the jar:
String yamlPath = "myYaml.yml";
InputStream in = new FileInputStream(new File(yamlPath));
InputStreamReader isr = new InputStreamReader(in);
BufferedReader input = new BufferedReader(isr);
yamlObj = (HashMap) javaYAML.load(input);
I then noticed this thread How to read a file from jar in Java? and found out that I needed a "/" before my path. I tried both methods above using the slash as well.
String yamlPath = File.seperator + ".." + File.separator + ".." + File.separator + ".." + File.separator + ".." + File.separator + "myYaml.yml";
OR
String yamlPath = File.seperator + "myYaml.yml";
I am completely lost on what to do about this error now. Is there something I am not getting about the jar structure? Why can my file not be found. Thanks in advance for any help / information.
Sorry, I forgot to mention where it is in the JAR: The class is in the following path: com/a/b/c/myclass.class The yaml is in the following path: myYaml.yml
Upvotes: 1
Views: 3677
Reputation: 11234
Somehow for me, i have to add '/' in front of the file name.
InputStream resourceAsStream = Xx.class.getResourceAsStream("/test.yml");
From java doc:
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'. Otherwise, the absolute name is of the following form: modified_package_name/name Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
And after i checked more detailed information, my solution is same as
InputStream in = Xx.class.getClassLoader().getResourceAsStream("test.yml");
Upvotes: 0
Reputation: 240898
File inside Jar is no longer a File, Change inputStream creation with this
InputStream in = YourClass.class.getResourceAsStream("myYaml.yml");
Assuming your .yml
file is at root of jar
Upvotes: 2
Reputation: 9474
InputStream is = this.getClass().getClassLoader().getResourceAsStream("file");
Upvotes: 0