假設(shè)我需要通過Process來執(zhí)行一個(gè)進(jìn)程,并且需要把進(jìn)程寫入InputStream里面的東西進(jìn)行讀取并分析,并且假設(shè)這個(gè)進(jìn)程會(huì)產(chǎn)生很多的字符串輸出。假定這個(gè)進(jìn)程是curl。以下代碼:try { // TODO add your handling code here:
StringBuilder sb = new StringBuilder();
ProcessBuilder pb = new ProcessBuilder("curl","http://www.sina.com.cn");
Process p = pb.start();
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is),4096);
String line = reader.readLine(); while(line != null){ //sb.append(line);
line = reader.readLine();
}
this.jTextArea1.append(sb.toString());
} catch (IOException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}在速度上似乎沒問題,但是將sb.append(line)加上去之后,明顯變得非常卡,并且CPU占用率特別高。這是為什么呢?
2 回答

HUH函數(shù)
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
你這里面while(line != null) 可能跳不出來,他會(huì)一直是true。你試試看是不是這個(gè)問題?

一只名叫tom的貓
TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
參考代碼如下:
InputStream is = null;try { ... is = p.getInputStream(); String text = IOUtils.toString(is, "GBK"); this.jTextArea1.append(text); } catch (...) { ... } finally { IOUtils.closeQuietly(is) }
添加回答
舉報(bào)
0/150
提交
取消