简体   繁体   中英

A class inside a jar file reads files outside the jar

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?

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 .

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM