我正在尝试将 shell 命令的输出读入字符串缓冲区,读取和添加值是可以的,除了添加的值是 shell 输出中每隔一行的事实。
例如,我有 10 行 od shell 输出,此代码仅存储 1, 3, 5, 7, 9, row 。
谁能指出为什么我无法使用此代码捕获每一行???
欢迎任何建议或想法:)
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 是同步的。
关于java - 存储 shell 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2690768/