Skip to content

opening a shell and interacting with its I/O in java

I am trying to open a shell (xterm) and interact with it (write commands and read the shell’s output)

Here is a sample of code which won’t work:

public static void main(String[] args) throws IOException {
    Process pr = new ProcessBuilder("xterm").start();
    PrintWriter pw = new PrintWriter(pr.getOutputStream());
    InputStreamReader in = new InputStreamReader(pr.getInputStream());

When I execute this program an “xterm” window opens and the “ls” command is not entered. Only when I close the window I get a “-1” printed and nothing is read from the shell


I know I can just use:
Process pr = new ProcessBuilder(“ls”).start();

To get the output, but I need the “xterm” opened for other uses

Thanks a lot



Your problem is that the standard input and output of the xterm process don’t correspond to the actual shell that is visible in the terminal window. Rather than an xterm you may have more success running a shell process directly:

Process pr = new ProcessBuilder("sh").start();
User contributions licensed under: CC BY-SA
9 People found this is helpful