kdev
kdev

Reputation: 291

FileNotFoundException while running as Jar - Java

I have written my java codes using eclipse and iam reading a file and processing the codes. The key.txt is present in the same folder as src .

BufferedReader br= new BufferedReader(new FileReader("KEY.txt"));

Now after i compile the jar and place both the jar and file in the same folder and execute iam getting FilenotFoundException. The program works if i run inside Eclipse reading the file perfectly.

The jar file and the key.txt always have to be in the same folder. Please let me know how can I solve this issue of FilenotFoundException.

Upvotes: 1

Views: 1585

Answers (2)

Thilo
Thilo

Reputation: 262494

The code you have opens a file in the current working directory, which is the directory where you started the Java process from.

This is completely unrelated to where the jar file is located.

How do you execute the jar file?

If the key file is right next to the jar file, this should work:

java -jar theJar.jar     

But this will not (because the path to the key is now "test/KEY.txt" ):

java -jar test/theJar.jar 

When you run a program in Eclipse, the current working directory is (usually) the project root folder.

An alternative to consider (if the file does not need to be edited by the user) is to put the key file into the jar file. Then it will not get lost, and you can load it via the classloader.

Another good option is to have the user provide the path to the file, via command line parameter or system property.

Or make a batch file / shell script that makes sure that you are always running from the proper directory.

Upvotes: 2

bhavesh1988
bhavesh1988

Reputation: 151

I think you should put these files with class file of the running class, because the current directory is the directory in which the class file is stored, not the source java file.

Upvotes: 0

Related Questions