Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- relative path of text file in main?

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?

like image 403
zProgrammer Avatar asked Mar 07 '13 20:03

zProgrammer


People also ask

How do I find the path of a text file?

Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).

What is the relative path of a file?

A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.

What are relative paths in Java?

A relative path is a path which doesn't start with the root element of the file system. It is simply the path needed in order to locate the file from within the current directory of your program. It is not complete and needs to be combined with the current directory path in order to reach the requested file.


2 Answers

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

String path = "src/data.txt"; 
like image 145
sab Avatar answered Sep 29 '22 21:09

sab


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

like image 29
chiffa Avatar answered Sep 29 '22 20:09

chiffa