我无法使用JFileChooser打开文本文件并在控制台中读取它,我尝试从一些教程中获取源代码,但我只获得了“文件处理”和“如何使用JFileChooser”的代码,我试过了将它们或其他东西结合起来只是为了解决这个问题,但我似乎无法做到这一点,我真的没有想法,任何帮助都会。
答案 0 :(得分:2)
如果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