java Runtime.exec 运行shell脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12833208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:23:42  来源:igfitidea点击:

java Runtime.exec to run shell script

javashellruntime.exec

提问by Lolly

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() 从 java 代码运行 shell 脚本。当我将参数作为字符串传递时,代码工作正常

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

为什么相同的脚本文件在作为 String 传递时起作用以及与 String 数组一起使用时抛出异常。有没有人遇到过这个问题。请帮助我使用字符串数组作为 Runtime.exec() 的参数来完成这项工作。提前致谢。

回答by Jayan

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