1

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?

joesan
  • 13,963
  • 27
  • 95
  • 232

5 Answers5

1

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

JamesB
  • 7,774
  • 2
  • 22
  • 21
0

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.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33
0
File file = new File("C:/folder/myFile.txt");

or if you know the relative path:

 File file = new File("../../path/myFile.txt");
AlexWien
  • 28,470
  • 6
  • 53
  • 83
0

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?

Community
  • 1
  • 1
peter_the_oak
  • 3,529
  • 3
  • 23
  • 37
0

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)