bmb
bmb

Reputation: 401

ProcessBuilder working in Linux but not Windows

I have a simple program that runs the echo command with ProcessBuilder, and the program works perfectly fine on my Linux machine, but it throws an IOException when running on Windows.

This is a simplified version of my program. It takes echo and hello as arguments for ProcessBuilder, and then saves the output into a string and prints the output. In Linux, the output is hello, and in Windows an IOException is caught.

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");
        }
    }
}

Does anyone know why this is not working in Windows?

Upvotes: 0

Views: 986

Answers (1)

Andreas
Andreas

Reputation: 159135

echo is not a program on Windows, it's an internal shell command*, so you need to invoke the command-line interpreter:

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

*) Reference: Wikipedia

Upvotes: 3

Related Questions