Storing Shell Output Storing Shell Output shell shell

Storing Shell Output


Here is the code that I typically use with BufferedReader in situations like this:

StringBuilder s = new StringBuilder();Process p = Runtime.getRuntime().exec("cat /proc/cpuinfo");BufferedReader input =    new BufferedReader(new InputStreamReader(p.getInputStream()));String line = null;//Here we first read the next line into the variable//line and then check for the EOF condition, which//is the return value of nullwhile((line = input.readLine()) != null){    s.append(line);    s.append('\n');}

On an semi-related note, when your code does not need to be thread safe it is better to use StringBuilder instead of StringBuffer as StringBuffer is synchronized.


Each time you call input.readLine() you're reading a new line. You're not doing anything with the one that you read inside the while() statement, you're just letting it fall on the floor. You'll need to temporarily store its value and process it within the body of the loop.