本文介绍了java Runtime.exec运行shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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")

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

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)

我也试过

      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

为什么传递时的脚本文件相同字符串工作,当与String数组一起使用时抛出异常。有没有人遇到过这个问题。请帮助我使用字符串数组作为Runtime.exec()的arugument。在此先感谢。

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.

推荐答案

第一个字符串成为命令。没有文件'sh test.sh'可以执行。

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

更改

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

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

(通常使用)

这篇关于java Runtime.exec运行shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:03