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(); 
     } 
} 
+0

什么错误,由于你? – 2012-07-27 18:40:40

+0

我没有得到任何错误,但它也不会像它应该写的那样写入.key文件。 – 2012-07-27 18:43:13

+0

您确定可以使用'Runtime.exec'使用输出重定向吗? – zneak 2012-07-27 18:43:43

您所使用的命令行格式为一个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" 
+0

该命令实际上等同于'Runtime.getRuntime()。exec(“prog”,new String [] {“”,“output”})' – Gumbo 2013-02-08 22:15:07

+0

Thanx,更新了答案 – anttix 2013-07-13 04:44:09

你不能因为他们的解释和由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(...); 
+0

如果您使用的命令像过滤器一样工作通过不断读取标准输入并同时写入标准输出。对于大量数据,缓冲区将被耗尽,所有写入操作都将被阻止。一个正确的解决方案是使用两个线程或非阻塞I/O来同时读写。 – anttix 2012-07-27 19:01:52

+0

@anttix,这是我希望人们阅读这些知道的细节;我只想指出这些流是存在的。 – zneak 2012-07-27 20:19:29

我测试,没关系。你可以试试。祝你好运

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}