javatextrelative-path

Reference a Text File with relative path in Java with the IntelliJ IDEA


I have a program that reads numbers from a .txt file. My problem is where to place this file, or how to reference it with a relative path to make this file accessible without using the absolute path.


Solution

  • When you try to open a file, it takes your current working path. For example this working tree:

    Project
    |->src
    |   |-->MyClass.java
    |   |-->MyFile1.txt
    |->res
       |->files
         |-->MyFile2.txt
    

    You can use new File("MyFile1.txt"); for MyFile1.

    or

    new File("./res/files/MyFile2.txt"); for MyFile2.