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

file, jar, java

Solution

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.

Problem

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?

Original source