java - 存储 Shell 输出

标签 java linux string shell buffer

我正在尝试将 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 是同步的。

关于java - 存储 Shell 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2690768/

相关文章:

java - Java中根据对象类型调用子类的方法

java - 将两个数组组合在一起?

c - linux gpio 驱动程序无法导出 GPIO

linux - 如何使用下一个单词前没有空格的变量?

c++ - 存储 NUL 字符 (ASCII 0)

java - 如何手动记录 JAX-RS 参数的 Swagger 数据模型?

java - 在 Java 中终止控制台应用程序

python - 来自 Python 多处理池类的意外行为

jQuery append 多行字符串

ruby - 在不使用 ruby​​ 中的 eval 的情况下将字符串转换为类名?