java getRuntime().exec() 不工作?

标签 java runtime exec

基本上,当我输入这些命令时 手动打开终端,筛选程序可以运行并写入一个 .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/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"

可能的修复:

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

参见:Unable to read InputStream from Java Process (Runtime.getRuntime().exec() or ProcessBuilder)

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

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

关于java getRuntime().exec() 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11693748/

相关文章:

java - 如何在 Hibernate 中限制 Java String 的创建?

java - 在运行时进程中执行 'start'

Java Eclipse 在运行时连续获取命令行参数

php - 在单个 exec php 语句中执行两个 shell 命令

linux - 异步获取 "slow protocols"的目录条目

javascript - 如何从在 Chart.JS 中运行的 PHP 生成 JSON

java - 为程序创建 .jar 文件

java - 为什么我可以实例化这个抽象类?

mysql - 列出运行时可以修改的所有变量

java - 使用 SwingWorker 更新 GUI