存储 Shell 输出
我试图将 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();
} }
}
I am trying to read the output of a shell command into a string buffer, the reading and adding the values is ok except for the fact that the added values are every second line in the shell output.
for example, I have 10 rows od shell output and this code only stores the 1, 3, 5, 7, 9, row .
Can anyone point out why i am not able to catch every row with this code ???
any suggestion or idea is welcomed :)
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();
} }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是我在这种情况下通常与 BufferedReader 一起使用的代码:
在半相关的注释中,当您的代码不需要线程安全时,最好使用 StringBuilder 而不是 StringBuffer,因为 StringBuffer 是同步的。
Here is the code that I typically use with BufferedReader in situations like this:
On an semi-related note, when your code does not need to be thread safe it is better to use StringBuilder instead of StringBuffer as StringBuffer is synchronized.
每次调用
input.readLine()
时,您都会读取一个新行。您没有对while()
语句中读到的内容做任何事情,只是让它掉到地板上。您需要临时存储其值并在循环体内处理它。Each time you call
input.readLine()
you're reading a new line. You're not doing anything with the one that you read inside thewhile()
statement, you're just letting it fall on the floor. You'll need to temporarily store its value and process it within the body of the loop.