Java- relative path of text file in main?

45,014

Solution 1

If you are using eclipse, place your text file in the root of the project folder, outside the /src and /bin folders. It should be now accessible via a relative path directly.

If you want to access a file in src folder, you have to append the /src/ prefix before the file path/name

Solution 2

Use the src/ prefix before the file path/name.

String path = "src/data.txt"; 

Solution 3

The path is relative to the directory you execute the "java" command.e.g.

 /opt/projects/myproject>$ java -cp <whatever your classpath is that contains your class files> com.mycompany.mypackage.MyJavaClass

in this case the MyJavaClass would find files relative to the directory
/opt/projects/myproject

There is another way to do this if you like: you can use load resources, which are found via the classpath mechanism.

 getClass().getResource("foo.txt");

You can see this posting for more info

Preferred way of loading resources in Java

Share:
45,014
zProgrammer
Author by

zProgrammer

Updated on November 08, 2020

Comments

  • zProgrammer
    zProgrammer over 3 years

    I was wondering how to specifiy a relative path name to a text file that is stored in my src folder of a java project. I would like to store a string with the path of this text file. For example if I had example.txt located in the src folder of my java project how would I go about finding its relative path? I am also doing this in my main so I'm having trouble using .getResource(). How would I do this? Thanks.

    My files path is as followed from the properties in eclipse /MyProject/src/data.txt

    I've tried:

    String path = "/MyProject/src/data.txt";

    But that doesn't work?

  • zProgrammer
    zProgrammer about 11 years
    you can't use "this" in a static method
  • zProgrammer
    zProgrammer about 11 years
    This is what I was looking for. Placing it outside the src folder worked.
  • Al-Alamin
    Al-Alamin over 6 years
    In windows to access a.txt file in src folder use "src/a.txt" not "/src/a.txt"
  • Will Wu
    Will Wu almost 6 years
    getClass is not available in a static context.