繁体   English   中英

使用JFileChooser和File handlng

[英]Using JFileChooser and File handlng

我无法使用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的基本帮助,请参阅本教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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