从文本文件 (JFileChooser) 中读取字符串并显示在 TextArea 中
Read string from text file (JFileChooser) and display in TextArea
当我想从我的磁盘中选择一个文本文件并在 TextArea 中显示其内容时,我有一些简单的应用程序。
private void fileChooserActionPerformed(java.awt.event.ActionEvent evt) {
File file = fileChooser.getSelectedFile();
try {
BufferedReader in;
in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while (line != null) {
textArea.setText(line + "\n");
line = in.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
}
我试过这样做,但它只读取文本文件的最后一行。
您为文件中的每一行调用 textArea.setText(line + "\n");
。所以首先你写第一行的内容,然后用第二行的内容覆盖它,等等。最后,只有最后一行的内容在textArea中。
要查看所有行,请像这样附加数据:
textArea.setText(textArea.getText() + "\n" + line);
当我想从我的磁盘中选择一个文本文件并在 TextArea 中显示其内容时,我有一些简单的应用程序。
private void fileChooserActionPerformed(java.awt.event.ActionEvent evt) {
File file = fileChooser.getSelectedFile();
try {
BufferedReader in;
in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while (line != null) {
textArea.setText(line + "\n");
line = in.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
}
我试过这样做,但它只读取文本文件的最后一行。
您为文件中的每一行调用 textArea.setText(line + "\n");
。所以首先你写第一行的内容,然后用第二行的内容覆盖它,等等。最后,只有最后一行的内容在textArea中。
要查看所有行,请像这样附加数据:
textArea.setText(textArea.getText() + "\n" + line);