Rajat
Rajat

Reputation: 151

Executable Java JAR can't find file path

I am facing problem while running executable .jar file via java -jar my.jar. I've created a project which contains a .sh file under src/main/resources/ path. In the code i am referring it to execute as:

Process pb = new ProcessBuilder("src/main/resources/stacktrace.sh",pid, traceFilePath,timeInMin).start();

It works just fine when I run my application from Intellij but when I export it to executable jar file and try to run it complains:

 Exception in thread "main" java.io.IOException: Cannot run program "src/main/resources/stacktrace.sh": error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)

Upvotes: 0

Views: 4122

Answers (1)

D.B.
D.B.

Reputation: 4713

The path you used in your ProcessBuilder is relative to the current working directory. When you run your code from your source project the path exists, but when running the jar the current working directory is different as you are not running it from within your source project. Therefore when your code attempts to find "src/main/resources/stacktrace.sh" it fails to find it.

For example, maybe your source project is located in:

/myCodeProject

So when you run your project your path resolves to:

/myCodeProject/src/main/resources/stacktrace.sh

When you run your jar perhaps you're running from somewhere like:

/opt/app/myApp

Therefore your path resolves to:

/opt/app/myApp/src/main/resources/stacktrace.sh

and it is this path which does not exist.

EDIT: As requested I am adding some ideas regarding how to correct the problem. However, your requirements are not clear as to where you want the file to live. Should it be outside the jar? Inside the jar? If it's outside will it be located in a specific constant path or relative to the jar?

  1. There's the obvious fix: put the file in the expected path so that it will be found.
  2. The other obvious fix: change the relative path so that it points to where the file is actually located.
  3. Build your jar such that the file is included inside the jar and use one of these methods to access it. Note that you may not be able to directly run the file, but you could read its content and generate an external temporary file and run that.

Upvotes: 1

Related Questions