在 JFrame 类中调用 File 方法(例如读取文本文件)是一个很好的做法,否则我该怎么办?谢谢回复。
这是我的代码:
private void filechooserButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt", "text"));
fileChooser.setAcceptAllFileFilterUsed(false);
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
resultTextArea.setText(null);
filePathTextField.setText(fileChooser.getSelectedFile().getAbsolutePath());
try (BufferedReader buffReader = new BufferedReader(new FileReader(new File(fileChooser.getSelectedFile().getAbsolutePath())))) {
String line;
while ((line = buffReader.readLine()) != null) {
resultTextArea.append(line + "\n");
}
} catch (Exception exc) {
JOptionPane.showMessageDialog(MainGUI.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
更新:我编辑了代码以使用 SwingWorker,所以我希望它比以前更好:
private class textFileReader extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() throws Exception {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt", "text"));
fileChooser.setAcceptAllFileFilterUsed(false);
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
resultTextArea.setText(null);
filePathTextField.setText(fileChooser.getSelectedFile().getAbsolutePath());
try (BufferedReader buffReader = new BufferedReader(new FileReader(new File(fileChooser.getSelectedFile().getAbsolutePath())))) {
String line;
while ((line = buffReader.readLine()) != null) {
resultTextArea.append(line + "\n");
}
} catch (Exception exc) {
JOptionPane.showMessageDialog(MainGUI.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
}
}
return null;
}
}
最佳答案
从字面上看,你的问题没有任何问题。由于您可以定义自己的方法,并且代码结构在某种程度上取决于开发人员,因此在碰巧扩展 JFrame
的类中进行文件处理在技术上没有任何问题。
也就是说,我认为您实际上要问的是“从 Swing 方法(例如 filechooserButtonActionPerformed()
)中执行文件 IO 是一个好习惯吗? “这个问题的答案明确是否定的——永远不要这样做。
这些方法由 UI 线程上的 Swing 调用,也称为 Event Dispatch Thread ,当 UI 线程等待这些方法返回时,您的应用程序将被卡住。它无法重绘,无法响应用户输入,什么都没有。因此,您希望将 IO 和其他长时间运行的工作卸载到其他线程。 Swing 文档中有一个很好的教程:Lesson: Concurrency in Swing .
关于java - 在 JFrame 类中调用 File 方法是一个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26518024/