2

I am using Runtime.getRuntime().exec() to run a shell script from Java code. The code works fine when I pass the parameter as string

      Runtime.getRuntime().exec("sh test.sh")

Since I have to pass additional arguments which are paths with spaces, so I replaced String with String array.

      String[] cmd = {"sh test.sh", "/Path/to my/resource file"};
      Runtime.getRuntime().exec(cmd)

I also tried with

      String[] cmd = {"sh test.sh"};
      Runtime.getRuntime().exec(cmd)

But neither of them worked. It's throwing an exception:

   java.io.IOException: Cannot run program "sh test.sh":
   java.io.IOException: error=2, No such file or directory

Why is the same script file when passed as String worked and when used with String array is throwing exception? How can I make this work with string array as argument to Runtime.exec()?

1

1 Answer 1

5

First string became the command. There is no file 'sh test.sh' to be executed.

Change

 String[] cmd = {"sh test.sh", "/Path/to my/resource file"};

to

String[] cmd = {"sh",  "test.sh", "/Path/to my/resource file"};

(In general use process builder API)

Sign up to request clarification or add additional context in comments.

3 Comments

What will be my first string in the array if I am going to run a batch file ?
Am not sure but try using String[] cmd = {"run", "test.bat", "/Path/to my/resource file"};
As far as I remember String[] cmd = {"test.bat", "/Path/to my/resource file"}; should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.