pandasticus
pandasticus

Reputation: 43

Java: Accessing a file that is in the same directory as .jar

I have a program that uses a file named list.txt to populate an ArrayList with its contents and then get a random line.

Here's the part that loads the file:

public class ReadList {
    private Scanner f;

    public void openFile(){

        try{
            f = new Scanner(new File("list.txt"));
        }catch(Exception e){
            System.out.println("File not found!");
        }
    }

However, it doesn't work when running it from a .jar file. I put the txt in the same directory and used f = new Scanner(new File("./list.txt")); yet it didn't work. I also tried some stuff I have found online but all I could manage to do is a) get a full path of the .jar with .jar included(/home/user/java/program.jar), and b) get a full path of the directory but without the / at the end(/home/user/java), which is a problem since I want this program to work on both Windows and Linux, therefore I can't simply do ("/home/user/java" + "/list.txt"), since Windows uses backslashes in paths.

So what's the simple way to just target the specific file(which will always be called list.txt) no matter which directory the file's in, as long as it's in the same place as the .jar?

Upvotes: 2

Views: 4102

Answers (1)

Dimitris Fousteris
Dimitris Fousteris

Reputation: 1111

Use this:

String filePath = System.getProperty("user.dir") + File.separator + "file.txt";

filePath will now contain the full path of file.txt which will be in the same dir as your jar.

Upvotes: 6

Related Questions