java Runtime.exec运行shell脚本 - 无法打开文件 [英] java Runtime.exec to run shell script - cannot open file
问题描述
我正在使用Runtime.getRuntime()。exec()从java代码运行shell脚本。
I am using Runtime.getRuntime().exec() to run a shell script from java code.
String[] cmd = {"sh", "build.sh", "/Path/to my/sh file"};
try{
Process proc = Runtime.getRuntime().exec( cmd );
}
catch(Exception e){
System.out.println("Exception is:"+e);
}
它在控制台中给出了以下输出:
It gives me the following output in console:
sh: Can't open build.sh
我在这里采取了一些错误的做法吗?无法理解为什么会发生这种情况。
Am I following some wrong approach here? Cannot make out why his happens.
编辑
根据此处的评论,我修改了 String [] cmd = {sh,build.sh,/ Path / to my / sh file};
改为 String [] cmd = {sh,/ Path / to my / sh file / build.sh,/ Path / to my / sh file};
。现在问题是这个脚本需要从特定路径执行。当我从命令提示符执行此脚本时,我首先将目录更改为该路径并执行它。我该如何修改此代码?
Based on the comment here, I have modified the String[] cmd = {"sh", "build.sh", "/Path/to my/sh file"};
to String[] cmd = {"sh", "/Path/to my/sh file/build.sh", "/Path/to my/sh file"};
. Now the problem is this script need to be executed from a particular path. When I execute this script from command prompt, I first change the directory to that path and execute it. How should I modify this code?
推荐答案
使用 ProcessBuilder
并设置进程的工作目录到你的脚本实际所在的目录:
Use a ProcessBuilder
and set the working directory of the process to the directory where your script actually is:
final ProcessBuilder pb = new ProcessBuilder("/bin/sh", "script.sh", "whatever",
"arguments", "go", "here");
pb.directory(new File("/path/to/directory"));
// redirect stdout, stderr, etc
final Process p = pb.start();
参见 ProcessBuilder
javadoc 。它包含了您可以执行的操作的示例。 Runtime.exec()
是passé:p
See the ProcessBuilder
javadoc. It contains an example of what you can do. Runtime.exec()
is passé :p
这篇关于java Runtime.exec运行shell脚本 - 无法打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!