Unable to get getInputStream from Runtime.getRunTime.exec ()

public class LinuxInteractor { public static String executeCommand(String command) { System.out.println("Linux command: " + command); try { Process p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader bf=new BufferedReader(new InputStreamReader( p.getInputStream())); String str=bf.readLine(); System.out.println("inputStream is::"+str); while( (str=bf.readLine()) != null) { System.out.println("input stream is::"+str); } System.out.println("process started"); } catch (Exception e) { System.out.println("Error occured while executing Linux command. Error Description: " + e.getMessage()); e.printStackTrace(); } } 

When I run the console script through it, it works. But through the Java program, InputStream(Str) comes as null .

Is there any other approach that I can use?

+4
source share
2 answers

Decision
You should try to read and execute in different threads.

The best alternative is to use ProcessBuilder , which takes care of the dirty work for you.
The code inside the try block might look something like this:

 /* Create the ProcessBuilder */ ProcessBuilder pb = new ProcessBuilder(commandArr); pb.redirectErrorStream(true); /* Start the process */ Process proc = pb.start(); System.out.println("Process started !"); /* Read the process output */ String line; BufferedReader in = new BufferedReader(new InputStreamReader( proc.getInputStream())); while ((line = in.readLine()) != null) { System.out.println(line); } /* Clean-up */ proc.destroy(); System.out.println("Process ended !"); 

See also this short demo .


Cause of the problem
According to Java Docs , waitFor() :

makes the current thread wait, if necessary, until the process represented by this process object is completed.

So, you are trying to get the output stream of the process after it is finished, therefore null .


(Sorry for the big revision of the answer.)

+5
source

You need to do this in a separate thread:

 Process process = Runtime.getRuntime().exec(command); LogStreamReader lsr = new LogStreamReader(process.getInputStream()); Thread thread = new Thread(lsr, "LogStreamReader"); thread.start(); public class LogStreamReader implements Runnable { private BufferedReader reader; public LogStreamReader(InputStream is) { this.reader = new BufferedReader(new InputStreamReader(is)); } public void run() { try { String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } } 

Then you need a second thread to process the input. And you can deal with stderr just like stdout.

+1
source

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


All Articles