user1269015
user1269015

Reputation:

Java file access

At the moment, in my java program, I am accessing a file that is in the project folder. When I'm loading the file its path is "./src/package/package/file.txt". When I build the program into an executable it dosen't work.

I would prefer the files to be outside of the .jar, but in the same folder, how would I got about this?

Samishal

Upvotes: 0

Views: 268

Answers (3)

Matt
Matt

Reputation: 11815

Because the relative path is relative to where your command prompt is when you execute the program, not from where the program lives.

You somehow need to tell the program where to find resources. Most people use a .sh/.bat script to figure out where the script itself lives, and either pass -D flags or set the classpath based on that location.

as a note, I $0 gives you the script as it was run on the command line in linux (it could be relative or absolute), and you can use dirname from there to find it's directory, and alter the java command line.

in windows %~dp0 gives you the directory of the batch script which was run, and you can use that to form your java command line.

Upvotes: 0

gigadot
gigadot

Reputation: 8969

You can use Class.getResourceAsStream to get the InputStream. It works for jar package too. It is not possible to access the file in jar file using File API directly.

InputStream ins = Class.getResourceAsStream("/gigadot/exp/resource.properties");

More details at http://blog.gigadot.net/2010/10/loading-classpath-resources.html

Upvotes: 0

David B
David B

Reputation: 2698

You can use a relative path if they are in the same folder, such as ./file.txt. That should carry over even with a compiled JAR.

Otherwise, if you're going to be using the same machine and are confident of the placement of the files, you could use an absolute path, however I don't recommend it.

Upvotes: 1

Related Questions