Harsh Yadav
Harsh Yadav

Reputation: 168

How to specify the directory as classpath in order to read a file in it using classloader while running java application?

Let's say there is a file abc.txt present in directory dir. I am trying to run a java application using following command java -cp dir;myjar.jar com.example.Main

And in Main class, I am trying to access this file like this getClass().getResource("/abc.txt"). But this is returning null. I am not sure what's wrong here. Any pointers will be appreciated.

Upvotes: 0

Views: 40

Answers (1)

Andreas
Andreas

Reputation: 159096

Since the file is in the root of the classpath directory, you need to use "/abc.txt", otherwise it's looking in the package folder for the class in question.

Just like the javadoc of getResource says:

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').

Upvotes: 2

Related Questions