java – 存储Shell输出

前端之家收集整理的这篇文章主要介绍了java – 存储Shell输出前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图将shell命令的输出读入字符串缓冲区,读取和添加值是正常的,除了添加的值是shell输出中的每隔一行这一事实.
例如,我有10行od shell输出,这段代码只存储1,3,5,7,9行.
任何人都可以指出为什么我不能用这个代码捕获每一行???
欢迎任何建议或想法:)

  1. import java.io.*;
  2. public class Linux {
  3. public static void main(String args[]) {
  4. try {
  5. StringBuffer s = new StringBuffer();
  6. Process p = Runtime.getRuntime().exec("cat /proc/cpuinfo");
  7. BufferedReader input =
  8. new BufferedReader(new InputStreamReader(p.getInputStream()));
  9. while (input.readLine() != null) {
  10. //System.out.println(line);
  11. s.append(input.readLine() + "\n");
  12. }
  13. System.out.println(s.toString());
  14. } catch (Exception err) {
  15. err.printStackTrace();
  16. } }
  17. }
最佳答案
以下是我在这种情况下通常与BufferedReader一起使用的代码

  1. StringBuilder s = new StringBuilder();
  2. Process p = Runtime.getRuntime().exec("cat /proc/cpuinfo");
  3. BufferedReader input =
  4. new BufferedReader(new InputStreamReader(p.getInputStream()));
  5. String line = null;
  6. //Here we first read the next line into the variable
  7. //line and then check for the EOF condition,which
  8. //is the return value of null
  9. while((line = input.readLine()) != null){
  10. s.append(line);
  11. s.append('\n');
  12. }

在半相关的注释中,当您的代码不需要线程安全时,最好使用StringBuilder而不是StringBuffer,因为StringBuffer是同步的.

猜你在找的Linux相关文章