每次我嘗試從.txt文件中讀取時,我都會得到一個NullPointerException. 我已經(jīng)查找了所有內(nèi)容,但無論如何都找不到答案。如果有人能告訴我我做錯了什么,那就太好了。 public class fileClassOpen implements ActionListener{ public void actionPerformed(ActionEvent e) { int dialog = chooser2.showOpenDialog(Other.this); if(dialog == JFileChooser.APPROVE_OPTION) { String path = chooser.getSelectedFile().getAbsolutePath(); try { FileReader fw = new FileReader(path); BufferedReader br = new BufferedReader(fw); while(br.readLine() != null) { txtArea.setText(br.readLine()); } } catch (IOException e1) { } } }}
3 回答

米琪卡哇伊
TA貢獻(xiàn)1998條經(jīng)驗 獲得超6個贊
您正在調(diào)用 br.readline() 兩次。因此,您最終一次閱讀兩行。也許,這就是為什么它在假設(shè)其他一切正常的情況下拋出 NullPointerException 的原因。我會做這樣的事情:
String line = "";
while ((line = br.readLine()) != null){
txtArea.setText(line);
}
另外,不要在沒有適當(dāng)?shù)?catch 語句的情況下嘗試吞下異常。

達(dá)令說
TA貢獻(xiàn)1821條經(jīng)驗 獲得超6個贊
嘗試使用txtArea.append( br.readLine() );
,而不是txtArea.setText(br.readLine())
作為textArea.append(str)
追加給定文本文檔的末尾。如果給定字符串為空或空,則不執(zhí)行任何操作。
添加回答
舉報
0/150
提交
取消