Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

java Runtime.exec to run shell script

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. Its throwing 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. Has anyone faced this issue. Please help me out to make this work with string array as arugument to Runtime.exec(). Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...