0

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

@EJP I had that in my original answer but removed it because I wasn't sure if it was required in Java. Is the dot prefix required for same-directory?
Is it not possible to specify a relative path to the file in the same directoy as the .jar
@DavidB yeah, didnt work, maybe I'm not being clear, I need the file to be outside the .jar but in the same directory as the .jar
java may be loading several jars, each in different directory, so there is no easy way to create a path relative to one specific jar (possible, but will be difficult). However, in java path are relative to the directory where you executed your program from, so you can put your txt file into that directory and it should work.
@Samishalt Update your question with code and maybe a picture of your file structure.
|
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.