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?
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).
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.
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.
Use the src/
prefix before the file path/name.
String path = "src/data.txt";
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With