【问题标题】:Dynamic File Reading动态文件读取
【发布时间】:2015-03-01 04:48:55
【问题描述】:

我在 Java Swing 中有一段代码,它浏览一个 txt 文件,然后在文本区域中打印文件的内容。这是完成工作的方法。出于某种我最有可能忽略的原因,每次测试代码时都会出现空指针异常。你能告诉我我做错了什么或者提供一个链接吗?

private void showText() {                
    try{
        //filePathInputField.setText(new File(file.getFile()).getAbsolutePath());
        FileReader fr = new FileReader(fileInputPathField.getText());
        BufferedReader br = new BufferedReader(fr);
        while((sourceText = br.readLine()) != null){
            sourceText += br.readLine();
        }
        sourceTextArea.setText(sourceText);
    } catch (Exception ex){
        showMessage();
        ex.printStackTrace();
    }
}

根据您的建议稍微更改代码后我收到的错误是:

java.io.FileNotFoundException: D:\Java\GUI Project Files\Crypto\Audio Specs.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:97)
    at java.io.FileReader.<init>(FileReader.java:58)

【问题讨论】:

标签: java swing io nullpointerexception filereader


【解决方案1】:

getClass().getResource() 用于打包文件(又名资源)。如果filePathInputField 包含文件系统中文件的路径,则该调用将返回null。您可以使用FilePath 的实例来访问它。

【讨论】:

  • 感谢您的输入,但我之前曾使用 File 进行过尝试,但结果相同。所以我从这里做了一点阅读并尝试了 URL。任何其他想法为什么会发生?
  • 之前我在 URL 的地方使用了这个代码模块:`sourceTextArea.setText(new File(file.getFile()).getAbsolutePath()); `
  • 抱歉之前的代码是:之前我在 URL 的地方使用了这个代码模块:` FileReader fr = new FileReader(new File(file.getFile()).getAbsolutePath()); `
  • 在这种情况下,new FileReader(new File(filePathInputField.getText())) 应该可以工作。如果没有,请提供更多信息(即 NPE 的完整堆栈跟踪)。
  • 这是我从堆栈跟踪中得到的错误:java.io.FileNotFoundException: Audio Specs.txt (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method)在 java.io.FileInputStream.(FileInputStream.java:138) 在 java.io.FileInputStream.(FileInputStream.java:97) 在 java.io.FileReader.(FileReader.java:58 )
猜你喜欢
  • 2020-05-05
  • 2016-07-26
  • 2021-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-27
  • 2020-06-22
  • 2010-10-26
相关资源
最近更新 更多