本文介绍了java getRuntime().exec()无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,当我在在终端上手动操作时,sift程序可以工作并写入.key文件,但是当我尝试从程序中调用它时,什么也没写.

Basically, when I type these commands inthe terminal by hand, the sift program works and writes a .key file, but when I try to call it from my program, nothing is written.

我正确使用exec()方法吗?我已经浏览了API,但似乎找不到错误的地方.

Am I using the exec() method correctly? I have looked through the API and I can't seem to spot where I went wrong.

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命令行,格式为:

The command line you are using is a DOS command line in the format:

prog < input > output

程序本身不带任何参数执行:

The program itself is executed with no arguments:

prog

但是代码中的命令执行为

However the command from your code is executed as

prog "<" "input" ">" "output"

可能的解决方法:

a)使用Java处理输入和输出文件

a) Use Java to handle the input and output files

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
...

请参阅:无法从中读取InputStream Java流程(Runtime.getRuntime().exec()或ProcessBuilder)

b)使用cmd.exe按原样执行命令

b) Use cmd.exe to execute the command as is

cmd.exe /c "prog < input > output"

这篇关于java getRuntime().exec()无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 07:01