Reputation: 33
So following is my project structure: a jar file (named patch.jar) and a resource folder;
so in jar file there is a class (named patch.class);
in resource folder there is a sub folder (named scripts) and in the sub folder there is a file (named patch.file) which i want my code to read.
the strange thing is when I set the file relative path, the code cannot read, however if i just set file name without path, it works.
File a = new File("./resource/scripts/patch.file"); //not work
File a = new File("./patch.file"); //works
I really got confused, is setting relative path supposed to do that?
Upvotes: 1
Views: 74
Reputation: 124646
Relative paths in File("...")
are relative from the working directory of the process. If File("some/path/file.txt")
works (or doesn't), that's because the file some/path/file.txt
exists (or doesn't) in the filesystem relative to the directory where the Java process runs. If you run on the command line, this path is relative to the directory you are in.
You cannot refer to a file inside a jar using File("...")
. To do that, you will need something like this:
InputStream is = this.getClass().getResourceAsStream("some/path/file.txt");
Upvotes: 0
Reputation: 691655
The fact that you have a jar is irrelevant. What matters is the location of the file relative to the current directory (the one you get when you execute pwd
). If you're in the directory /Home/aken
, and execute the command
less ./resources/scripts/patch.file
it will try to open and display the file /Home/aken/resources/scripts/patch.file
.
The same goes with relative file paths in Java. If you're in the directory /Home/aken
, and execute
java -cp patch.jar patch
and the code of the class uses
new File("./resource/scripts/patch.file");
Then java will try to open the file /Home/aken/resources/scripts/patch.file
.
If you're in /foo/bar
and execute the command
java -cp /Home/aken/patch.jar patch
then java will search for the file relative to the current directory, which is /foo/bar
. And it will thus open the file /foo/bar/resources/scripts/patch.file
.
Upvotes: 1