user2340612
user2340612

Reputation: 10703

Java jar can't access resources

I need to execute a jar file which uses some files located in some subfolders.

For example the directory tree can be like this:

jar_root/
├── executable.jar
├── folder1/
│    └── required_file1.txt
│
├── folder2/
│    └── required_file2.txt
│
├── other_folder/
│   └── ...
└── other_file.txt

In this example executable.jar needs to access required_file1 and required_file2.

I need to execute the jar from another directory, so I tried this command:

java -cp /path/to/jar_root/ -jar /path/to/jar_root/executable.jar <options>

But what I got is a FileNotFoundException on required_file1 (I guess the same Exception will be raised for required_file2)

How can I make the jar work?

Note that I cannot modify the jar, so I can't use getResourceAsStream, as suggested by this (and other) answer(s).

Upvotes: 1

Views: 783

Answers (1)

janos
janos

Reputation: 124646

It depends on how the code in the jar tries to access the files. If by relative path, that can only work if you start the program from the appropriate working directory, for example:

cd /path/to/jar_root/ 
java -jar executable.jar <options>

An alternative is to reference the files by absolute path, or relative from classpath instead of filesystem path.

Upvotes: 2

Related Questions