Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a batch file from Java does not give access to full PATH

I am writing a Java utility that executes a batch file to generate a PDF using the DITA toolkit and Apache FOP. It finishes by using pdftk to watermark the front page. If I execute the batch file in Windows using Start>CMD, this line in the batch file works:

pdftk "%DITA_OUTPUT%book.pdf" multibackground C:\doc_build_system\watermark.pdf output "%DITA_OUTPUT%external.pdf" compress verbose

When I execute the batch file by Runtime.exec() the same line fails.

The cause of the failure is that the PATH variable is incomplete when executed through Java. It should have an entry like:

C:\Program Files (x86)\PDFtk Server\bin\

...but it does not. I tried to force execution through CMD by invoking runtime.exec("cmd /c batchfile.bat") (rather than just directly invoking the batchfile) but this also had no effect.

Any ideas?

like image 856
Agnes Avatar asked Mar 25 '26 04:03

Agnes


1 Answers

You can try to set the path manualy before your start your java in cmd:

start cmd.exe. Then type:

SET PATH=%PATH%;C:\Program Files (x86)\PDFtk Server\bin
java MyProgram

If that is working you have to check if edited the right PATH variable. In Windows you can have different PATH environment variables for each user, plus there is one system-wide PATH variable (see screenshot) that will always be applied and combined with the user variables. enter image description here

e.g. if you did set the path for your user and then use administrator for elevated rights to execute java, the PATH won't be set properly.

Make sure to use the system variable.

Also make sure to restart windows after you did edit the variable, because open applications and consoles will usually only fetch environment variables once at start up.

like image 178
Jesko R. Avatar answered Mar 26 '26 20:03

Jesko R.