Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read from a file that is in the same folder as the .jar file

Tags:

java

file

jar

Is there a way to read from a file that is in the same folder as the .jar file? I am trying to create a java program that has to read from a file when I turn in my assignment. I do not know where the file or program will be held once I turn it over so I dont think I can encode the directory of the held file. Is this possible? The problem is that i have to upload the file to a CSX hosts server which is a linux server and run it from there. If I dont put a path before the file will it just search its current folder location?

like image 290
shinjuo Avatar asked Feb 19 '13 21:02

shinjuo


2 Answers

You can get the location of the JAR file containing any specific class via:

URL url = thisClass.getProtectionDomain().getCodeSource().getLocation();

From there it is easy to relativize a URL to the desired file.

like image 195
user207421 Avatar answered Oct 21 '22 05:10

user207421


As noted in the comments, this works only if you run the command from the directory the jar is in.

(In the context of a desktop application)
To access a file that's in the current directory of the jar, your path to the file should be preceded by a dot. Example:

String path = "./properties.txt";
FileInputStream fis = new FileInputStream(path);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
// Read the file contents...

In this example, there is a text file called properties.txt in the same directory as the jar.
This file will be read by the program contained in the jar.

Edit: you said the filename would not change, and this answer applies given that you know the name beforehand, of course, should you prefer to hardcode it.

like image 20
afsantos Avatar answered Oct 21 '22 05:10

afsantos