简体   繁体   English

java Runtime.exec运行shell脚本

[英]java Runtime.exec to run shell script

I am using Runtime.getRuntime().exec() to run a shell script from java code. 我使用Runtime.getRuntime()。exec()从java代码运行shell脚本。 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数组替换了String。

      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. 为什么在作为String工作时传递相同的脚本文件,并且当与String数组一起使用时抛出异常。 Has anyone faced this issue. 有没有人遇到过这个问题。 Please help me out to make this work with string array as arugument to Runtime.exec(). 请帮助我使用字符串数组作为Runtime.exec()的arugument。 Thanks in advance. 提前致谢。

First string became the command. 第一个字符串成了命令。 There is no file 'sh test.sh' to be executed. 没有要执行的文件'sh test.sh'。

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 ) (一般使用流程构建器API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM