简体   繁体   中英

Using JFileChooser and File handlng

我无法使用JFileChooser打开文本文件并在控制台中读取它,我尝试从一些教程中获取源代码,但我只获得了“文件处理”和“如何使用JFileChooser”的代码,我试图将它们组合起来或者只是为了解决这个问题,但我似乎无法做到这一点,我真的没有想法,任何帮助都会做。

If the JFileChooser returns JFileChooser.APPROVE_OPTION , using .getSelectedFile() will return a File object

File file;
JFileChooser chooser = new JFileChooer();
int returnValue = JFileChooser.showOpenDialog(this);
if (returnVal = JFileChooser.APPROVE_OPTION){
    file = chooser.getSelectedFile();
}

If you understand how to you basic I/O, then you should know what to do with that file.

Something fairly simple would just be something like this

try {
    BufferedReader in = new BufferedReader(new FileReader(file));
    String line;
    while ((line = in.readLine()) != null){
        textArea.append(line + "\n");
} catch(IOException ex){
    ex.printStackTrace();
}

  • Another option is to use the JTextComponent#read() method

  • Another option is to use a JEditorPane and just use its setPage() method

     JEditorPane document = new JEditorPane(); File file = fileChooser.getSelectedFile(); try { document.setPage(file.toURI().toURL()); } catch(Exception e) { e.printStackTrace(); } 

If you need basic help with I/O, see this tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM