[英]Storing Shell Output
我試圖將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是同步的。
每次調用input.readLine()
您都會讀取一個新行。 你沒有對你在while()
語句中讀到的那個做任何事情,你只是讓它落在了地板上。 您需要臨時存儲其值並將其處理在循環體內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.