Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect Linux command output

I am now on a linux machine. I have a Java program which would run some linux command, for example ps, top, list or free -m.

The way to run a command in Java is as follows:

Process p = Runtime.getRuntime().exec("free -m");

How could I collect the output by Java program? I need to process the data in the output.

like image 262
user84592 Avatar asked Jun 22 '11 14:06

user84592


People also ask

How do I capture a terminal output in Linux?

Simply right-click on the terminal and press “Copy output as HTML.” This will, then, load the terminal text into your clipboard. From there, you can paste it to any text editor.


2 Answers

Use Process.getInputStream() to get an InputStream that represents the stdout of the newly created process.

Note that starting/running external processes from Java can be very tricky and has quite a few pitfalls.

They are described in this excellent article, which also describes ways around them.

like image 184
Joachim Sauer Avatar answered Oct 09 '22 22:10

Joachim Sauer


To collect the output you could do something like

 Process p = Runtime.getRuntime().exec("my terminal command");

  p.waitFor();
  BufferedReader buf = new BufferedReader(new InputStreamReader(
          p.getInputStream()));
  String line = "";
  String output = "";

  while ((line = buf.readLine()) != null) {
    output += line + "\n";
  }

  System.out.println(output);

This would run your script and then collect the output from the script into a variable. The link in Joachim Sauer's answer has additional examples of doing this.

like image 25
Nick DeFazio Avatar answered Oct 09 '22 21:10

Nick DeFazio