java getRuntime()。exec()不工作?
问题描述:
基本上,当我手工在终端上键入这些命令时,筛选程序工作并写入一个.key文件,但是当我尝试从我的程序中调用它时,没有任何内容被写入。java getRuntime()。exec()不工作?
我正确使用exec()方法吗?我已经浏览了API,我似乎无法找到我出错的地方。
public static void main(String[] args) throws IOException, InterruptedException
{
//Task 1: create .key file for the input file
String[] arr = new String[3];
arr[0] = "\"C:/Users/Wesley/Documents/cv/final project/ObjectRecognition/sift/siftWin32.exe\"";
arr[1] = "<\"C:/Users/Wesley/Documents/cv/final project/ObjectRecognition/sift/cover_actual.pgm\"";
arr[2] = ">\"C:/Users/Wesley/Documents/cv/final project/ObjectRecognition/sift/keys/cover_actual.key\"";
String command = (arr[0]+" "+arr[1]+" "+arr[2]);
Process p=Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
}
答
您所使用的命令行格式为一个DOS命令行:
prog <input> output
程序本身不带参数运行:
prog
个
但是从你的代码的命令作为
prog "<" "input" ">" "output"
执行可能的修正:
一)使用Java来处理输入和输出文件
Process process = Runtime.getRuntime().exec(command);
OutputStream stdin = process.getOutputStream();
InputStream stdout = process.getInputStream();
// Start a background thread that writes input file into "stdin" stream
...
// Read the results from "stdout" stream
...
参见:Unable to read InputStream from Java Process (Runtime.getRuntime().exec() or ProcessBuilder)
b)使用cmd.exe执行该命令,原因是
cmd.exe /c "prog <input> output"
答
你不能因为他们的解释和由shell执行与Runtime.exec
使用重定向(<
和>
)。它只适用于一个可执行文件及其参数。
延伸阅读:
答
您不能对Runtime.exec
使用输入/输出重定向。另一方面,同样的方法返回一个Process
对象,你可以访问它的输入和输出流。
Process process = Runtime.exec("command here");
// these methods are terribly ill-named:
// getOutputStream returns the process's stdin
// and getInputStream returns the process's stdout
OutputStream stdin = process.getOutputStream();
// write your file in stdin
stdin.write(...);
// now read from stdout
InputStream stdout = process.getInputStream();
stdout.read(...);
答
我测试,没关系。你可以试试。祝你好运
String cmd = "cmd /c siftWin32 <box.pgm>a.key";
Process process = Runtime.getRuntime().exec(cmd);
答
*对于特殊字符,通常会导致问题: 此代码工作正常,即使像文件名: “1 - 1卷(Fronte).JPG”
String strArr[] = {"cmd", "/C", file.getCanonicalPath()};
Process p = rtObj.exec(strArr);///strCmd);
也同意,此处不支持重定向。
测试在Windows 7 {guscoder:912081574}
什么错误,由于你? – 2012-07-27 18:40:40
我没有得到任何错误,但它也不会像它应该写的那样写入.key文件。 – 2012-07-27 18:43:13
您确定可以使用'Runtime.exec'使用输出重定向吗? – zneak 2012-07-27 18:43:43