【问题标题】:java Runtime.exec to run shell scriptjava Runtime.exec 运行 shell 脚本
【发布时间】:2012-10-11 06:07:40
【问题描述】:

我正在使用 Runtime.getRuntime().exec() 从 java 代码运行 shell 脚本。当我将参数作为字符串传递时,代码工作正常

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

由于我必须传递带有空格的路径的附加参数,所以我用字符串数组替换了字符串。

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

我也试过

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

但他们都没有工作。它抛出异常

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

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

【问题讨论】:

标签: java shell runtime.exec


【解决方案1】:

第一个字符串成为命令。没有要执行的文件“sh test.sh”。

改变

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

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

(一般使用process builder API

【讨论】:

  • 如果我要运行批处理文件,数组中的第一个字符串是什么?
  • 不确定,但请尝试使用String[] cmd = {"run", "test.bat", "/Path/to my/resource file"};
  • 据我所知String[] cmd = {"test.bat", "/Path/to my/resource file"}; 应该可以工作。
猜你喜欢
  • 1970-01-01
  • 2012-02-19
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 2012-11-22
相关资源
最近更新 更多