Reputation: 165
I have a java project structure, built in eclipse as below
--Workspace/ProjectName/bin(Where .class files exist)
|
/src(where source files i.e, java files exist)
|
/text(where a .txt file named Requests.txt present)
|
/common.properties(A property file)
when I checked present location using
URL location = FileToString.class.getProtectionDomain().getCodeSource().getLocation();
got o/p as file:/D:/Workspace_Nandan/ProjectName/bin/
so, I used a code
contents = new String(Files.readAllBytes(Paths.get("../ProjectName/text/Requests.txt")));
with relative path ../ProjectName/text/Requests.txt as mentioned above. And its working fine,it's reading text file when I run it.
But the same thing when I convert the project to executable jar with same relative path in the code and place it in the same bin folder and Requests.txt inside ProjectName/text folder it can't access the text file mentioned.
throws java.nio.file.NoSuchFileException.
Is there any changes should I make in relative path for executable jar? I tried many solutions given in stackoverflow but din't find it useful/appropriate to my issue.
Please help. Thanks in advance.
Upvotes: 0
Views: 2019
Reputation: 126
Well this depends on your current working directory. if you execute your jar under Workspace/ProjectName as java -jar bin/"yourjarname".jar the path to get the file that you want should be "text/Requests.txt". Your IDE is working under Workspace/ProjectName, that's your current dir in java when you execute from there.
Upvotes: 2
Reputation: 320
When you run your code via Eclipse, the base directory from which relative paths are figured out is your project folder ProjectName. So, if you base directory is ProjectName and look for you text file in ../ProjectName/text/Requests.txt, you'll find it!
If place your executable jar in the bin directory, the base directory is the directory your jar file is located in and the relative path you use should be ../text/Requests.txt
I suggest you change your relative path to "text/Requests.txt" and move your jar file to the ProjectName directory.
Upvotes: 1