Opening a shell and interacting with its input / output in java

I try to open a shell (xterm) and interact with it (write commands and read shell output)

Here is an example of code that will not 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 run this program, the xterm window opens and the ls command is not entered. Only when I close the window do I get "-1" and nothing is read from the shell

IMPORTANT -

I know I can just use:
Process pr = new ProcessBuilder ("ls"). Start ();

To get the result, but I need an "xterm" open for other purposes

thanks a lot

+4
source share
2 answers

Your problem is that the standard input and output of the xterm process do not match the real shell that is visible in the terminal window. Instead of xterm, you may have more success when starting the shell process:

 Process pr = new ProcessBuilder("sh").start(); 
+4
source

Here's a complete basic Java example of how to interact with shell on java 8 (actually it is easy to do this on java 4, 5,6 independently)

Output example

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

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(); } } } 
+1
source

Source: https://habr.com/ru/post/1446651/


All Articles