我试图将shell命令的输出读入字符串缓冲区,读取和添加值是正常的,除了添加的值是shell输出中的每隔一行这一事实.
例如,我有10行od shell输出,这段代码只存储1,3,5,7,9行.
任何人都可以指出为什么我不能用这个代码捕获每一行???
欢迎任何建议或想法:)
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();
} }
}
最佳答案
以下是我在这种情况下通常与BufferedReader一起使用的代码:
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);
s.append('\n');
}
在半相关的注释中,当您的代码不需要线程安全时,最好使用StringBuilder而不是StringBuffer,因为StringBuffer是同步的.