java getRuntime()。exec()不工作?
基本上,当我手动在终端中键入这些命令时,sift程序工作并写入.key文件,但是当我尝试从程序中调用它时,什么也没写。
我正确使用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/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"
可能的修复:
a)使用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 ...
请参阅: 无法从Java进程读取InputStream(Runtime.getRuntime()。exec()或ProcessBuilder)
b)使用cmd.exe按原样执行命令
cmd.exe /c "prog < input > output"
您不能将重定向( <
和>
)与Runtime.exec
因为它们由shell解释和执行。 它只适用于一个可执行文件及其参数。
进一步阅读:
您不能使用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 a.key"; Process process = Runtime.getRuntime().exec(cmd);
*对于通常会导致问题的特殊字符:即使使用以下文件名,此代码也能正常工作:“1 – Volume 1(Fronte).jpg”
String strArr[] = {"cmd", "/C", file.getCanonicalPath()}; Process p = rtObj.exec(strArr);///strCmd);
同意,此处不支持重定向。
在Windows 7上测试{guscoder:912081574}