Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
    pw.println("ls");
    pw.flush();
    InputStreamReader in = new InputStreamReader(pr.getInputStream());
    System.out.println(in.read());
}

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

IMPORTANT-

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

like image 856
royeet Avatar asked Nov 17 '12 14:11

royeet


People also ask

How do I invoke jshell?

To start JShell, enter the jshell command on the command line. JDK 9 must be installed on your system. If your path doesn't include java-home/jdk-9/bin , start the tool from within that directory.

How to open a file in the Java Shell?

The Java Shell provides the /open <filename> command that allows you to open a file and read its contents and snippets and command, which is very useful for reusing commands or code. The file can contains any Java code and valid jshell ’s commands. For example, the following command imports the code in Person.java file to the shell:

What is I/O file in Java?

Java - Files and I/O. The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc.

How to execute a shell command from Java code?

Overview With this tutorial we'll illustrate the two ways of executing a shell command from within Java code. The first is to use the Runtime class and call its exec method. The second and more customizable way, will be to create and use a ProcessBuilder instance. 2. Operating System Dependency

What is IO package in Java?

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc.


2 Answers

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();
like image 156
Ian Roberts Avatar answered Sep 18 '22 16:09

Ian Roberts


Here a full java main example of how to interact with shell on java 8 (is really simple do that on java 4,5,6 whatever)

Example of output

$ javac Main.java
$ java Main
echo "hi"
hi

The code

import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;


public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {

        final List<String> commands = Arrays.asList("/bin/sh");
        final Process p = new ProcessBuilder(commands).start();

        // imprime erros
        new Thread(() -> {
            BufferedReader ir = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String line = null;
            try {
                while((line = ir.readLine()) != null){
                    System.out.printf(line);
                }
            } catch(IOException e) {}
        }).start();

        // imprime saida
        new Thread(() -> {
            BufferedReader ir = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            try {
                while((line = ir.readLine()) != null){
                    System.out.printf("%s\n", line);
                }
            } catch(IOException e) {}
        }).start();

        // imprime saida
        new Thread(() -> {
            int exitCode = 0;
            try {
                exitCode = p.waitFor();
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            System.out.printf("Exited with code %d\n", exitCode);
        }).start();


        final Scanner sc = new Scanner(System.in);
        final BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
        final String newLine = System.getProperty("line.separator");
        while(true){
            String c = sc.nextLine();
            bf.write(c);
            bf.newLine();
            bf.flush();
        }

    }

}
like image 36
deFreitas Avatar answered Sep 20 '22 16:09

deFreitas