Reputation: 15385
I have a folder called lib that contains all my Jar files and in one of the Jar files class, I have a main method which is called by a batch file. In the same folder location as my lib, I have another folder structure path/to/a/resource/myresource.txt
How can I load this file from a class inside the Jar file? I tried the following and both resulted in null:
getClass().getResource("path/to/a/resource/myresource.txt")
getClass().getClassLoader().getResource("path/to/a/resource/myresource.txt")
Any ideas? Even with an absolute path, it failed! Any suggestions?
Upvotes: 1
Views: 1517
Reputation: 7894
You can use:
getClass().getResourceAsStream("path/to/a/resource/myresource.txt")
However, for this to work, you need to add the path '.' to the Class-Path entry of the JAR's MANIFEST.MF file.
http://docs.oracle.com/javase/tutorial/deployment/jar/downman.html
Upvotes: 1
Reputation:
You can either load the file from file system
new FileReader(relativeOrAbsoluteFilesystemLocation)
or you can add the directory in question to your classpath:
java -cp "lib/*;lib" ...
and then use your original method.
(Unix uses :
rather than ;
as classpath separator)
Upvotes: 0
Reputation: 3710
Your path seems not to be precise enough. Further, this question has been worked before.
Have a look here:
How to Load File Outside of, but Relative to, the JAR?
How to get the path of a running JAR file?
Upvotes: 0
Reputation: 28727
File file = new File("C:/folder/myFile.txt");
or if you know the relative path:
File file = new File("../../path/myFile.txt");
Upvotes: 0
Reputation: 9946
Two things you tried are used to read files from class-path since this folder is not on your classpath you can read it directly with any of the java File IO classes.
Upvotes: 0