【问题标题】:ProcessBuilder working in Linux but not WindowsProcessBuilder 在 Linux 但不能在 Windows 中工作
【发布时间】:2021-01-26 06:48:19
【问题描述】:

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

这是我的程序的简化版本。它将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 中不起作用?

【问题讨论】:

    标签: java windows ioexception processbuilder


    【解决方案1】:

    echo不是Windows上的程序,它是一个内部shell命令*,所以你需要调用命令行解释器:

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

    *) 参考:Wikipedia

    【讨论】:

    • 这是有道理的。谢谢!
    猜你喜欢
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    相关资源
    最近更新 更多