ProcessBuilder在Linux中工作,但在Windows中不工作

问题描述

我有一个简单的程序,它使用echo运行ProcessBuilder命令,该程序在我的Linux机器上运行良好,但是在Windows上运行时会抛出IOException。 / p>

这是我程序的简化版本。它使用echohello作为ProcessBuilder的参数,然后将输出保存到字符串中并打印输出。在Linux中,输出hello,在Windows中为IOException

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestPB {
    public static void main(String[] args) throws InterruptedException {
        ProcessBuilder pb = new ProcessBuilder("echo","hello");
        try {
            Process process = pb.start();
            BufferedReader readProcessOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String output = "";
            String line = "";
            while ( (line = readProcessOutput.readLine()) != null) {
                output += line;
                output += System.getProperty("line.separator");
            }

            process.waitFor();
            if(output.length() > 0) {
                System.out.println(output.substring(0,output.length() -1));
            } else {
                System.out.println("No result");
            }
        } catch (IOException io) {
            System.out.println("IOException thrown");
        }
    }
}

有人知道为什么这在Windows中不起作用吗?

解决方法

echo不是Windows上的程序,它是内部shell命令 * ,因此您需要调用命令行解释器:

ProcessBuilder pb = new ProcessBuilder("cmd.exe","/c","echo","hello");

*)参考:Wikipedia

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...