views:

62

answers:

3

Hello everybody,

I am trying to read the output of a shell command into a string buffer, the reading and adding the values is ok except for the fact that the added values are every second line in the shell output. for example, I have 10 rows od shell output and this code only stores the 1, 3, 5, 7, 9, row . Can anyone point out why i am not able to catch every row with this code ??? any suggestion or idea is welcomed :)

import java.io.*;

public class Linux {

public static void main(String args[]) {


    try {
    StringBuffer s = new StringBuffer();

Process p = Runtime.getRuntime().exec("cat /proc/cpuinfo");
BufferedReader input =
        new BufferedReader(new InputStreamReader(p.getInputStream()));
while (input.readLine() != null) {
    //System.out.println(line);
s.append(input.readLine() + "\n");

}
System.out.println(s.toString());

} catch (Exception err) { err.printStackTrace(); } } }

+2  A: 

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.

Jim Kiley
Hello,Thanks for your reply.I tried with this also while (s.append(input.readLine()) != null) { //System.out.println(line); s.append(input.readLine() + "\n"); }But the code gets stucked, can you paste me an example ??
Emil Radoncik
+3  A: 

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 null
while((line = input.readLine()) != null){
    s.append(line+'\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.

M. Jessup
A: 

Thanks M. Jessup the code helped me a lott...

Emil Radoncik