0

I am working on a project wherein I have to call my shell script stored at the location where my java files reside.I am currently calling the shell script by giving a hard-coded (absolute) path.I want to make my script run by giving a relative path.Currently I am running my script via this code in Java:

try {
     ProcessBuilder pb2 = new ProcessBuilder("/bin/bash", "/Users/umang/Documents/script.sh", arg);
     Process scriptexec = pb2.start();
     scriptexec.waitFor();
    } catch (Exception e) {
             e.printStackTrace();
             }

Here the arg is the location of the file on which the script runs.The current Implementation works well but the Issue is I have to store my script at some location on the server.Its a webapp which is deployed on apache-tomcat server by making a war file. It would be good to have a relative path and store the script inside the war file when it is being generated.

Attempt #1:

final File executorDirectory = new File("A/B/C/D/E/F/G/H/");
      try {
          ProcessBuilder pb2 = new ProcessBuilder("/bin/bash","combiner.sh",arg);
          pb2.directory(executorDirectory);
          Process scriptexec = pb2.start();
          scriptexec.waitFor();
          System.out.println("Script executed successfully");
      } catch (Exception e) {
          e.printStackTrace();
      }

A/B/C/D/E/F/G/H/ location where my script resides from the top of the application Error: File not found error -2 JavaIOException()

Attempt #2

URL loc=ClassLoader.getSystemResource("script.sh");
try {
     ProcessBuilder pb2 = new ProcessBuilder("/bin/bash", "/Users/umang/Documents/script.sh", arg);
     Process scriptexec = pb2.start();
     scriptexec.waitFor();
    } catch (Exception e) {
             e.printStackTrace();
             }

Error: loc does not get me the path for the script location.In the debugger tool I figured out it gets null.

Since the ClassLoader.getSystemResource returns a URL and ProcessBuilder only accepts String I cannot directly append them.

1 Answers1

0

If this is deployed in tomcat try to put your script in the WEB-INF of your war. Now assuming you start the process from a servlet you could use

ServletContext ctx = getContext();
String pathForProcessBuilder = ctx.getRealPath("/WEB-INF/script.sh");

If you don't want to use the ServletContext, try using

getClass().getClassLoader().getResource("/WEB-INF/script.sh")

instead of using ClassLoader (in order to make sure you use the "correct" classloader, i.e. the one which loaded your class)

Ueli Hofstetter
  • 2,409
  • 4
  • 29
  • 52