我在使用 JFileChooser 打开文本文件并在控制台中读取它时遇到问题,我尝试从一些教程中获取源代码,但我只获得了“文件处理”和“如何使用 JFileChooser”的代码,并且我尝试了将它们结合起来或只是为了解决问题,但我似乎做不到,我真的没有想法了,任何帮助都可以。
最佳答案
如果 JFileChooser 返回 JFileChooser.APPROVE_OPTION
,使用 .getSelectedFile()
将返回 File
对象
File file;
JFileChooser chooser = new JFileChooer();
int returnValue = JFileChooser.showOpenDialog(this);
if (returnVal = JFileChooser.APPROVE_OPTION){
file = chooser.getSelectedFile();
}
如果您了解如何进行基本 I/O,那么您应该知道如何处理该文件。
相当简单的事情就是这样
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
while ((line = in.readLine()) != null){
textArea.append(line + "\n");
} catch(IOException ex){
ex.printStackTrace();
}
<小时/>
另一个选项是使用
JTextComponent#read()
方法另一个选项是使用
JEditorPane
只需使用它的setPage()
方法JEditorPane document = new JEditorPane(); File file = fileChooser.getSelectedFile(); try { document.setPage(file.toURI().toURL()); } catch(Exception e) { e.printStackTrace(); }
如果您需要有关 I/O 的基本帮助,请参阅 this tutorial
关于java - 使用 JFileChooser 和文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20920360/