加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

java – 存储Shell输出

发布时间:2020-12-13 19:00:09 所属栏目:Linux 来源:网络整理
导读:我试图将shell命令的输出读入字符串缓冲区,读取和添加值是正常的,除了添加的值是shell输出中的每隔一行这一事实. 例如,我有10行od shell输出,这段代码只存储1,3,5,7,9行. 任何人都可以指出为什么我不能用这个代码捕获每一行??? 欢迎任何建议或想法:) import

我试图将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是同步的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读