【问题标题】:Swing GUI IOException and FileNotFoundExceptionSwing GUI IOException 和 FileNotFoundException
【发布时间】:2016-08-18 12:30:13
【问题描述】:

我正在尝试通过单击按钮使用 WindowBuilder 将文本文件中的数据加载到 JList 中。正如您从下面的代码中看到的那样,我遇到了一些我似乎无法修复的异常。导入 java.io.FileReader 没有帮助。

我有一个单独的类文件,其中包含我的分数向量的代码。

    JButton btnLoadData = new JButton("Load Data");
    btnLoadData.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            String sLine;

            Vector<Score> scoreVec = new Vector<Score>();

            //Here I am getting a FileNotFoundException for (new FileReader("scores.txt")
            BufferedReader in = new BufferedReader(new FileReader("scores.txt")); 


            //Here I am getting an IOException for in.readLine()
            while ((sLine = in.readLine()) != null)
            {
                scoreVec.addElement(new Score(sLine));
            }

            //this is also throwing an IOException
            in.close();


            //Placeholders until I get the rest of the program working
            System.out.println(scoreVec.get(1).name);
            System.out.println(scoreVec.get(1).country);
        }
    });
    btnLoadData.setBounds(10, 227, 89, 23);
    frame.getContentPane().add(btnLoadData);

【问题讨论】:

  • new FileReader("scores.txt") 将高分放在保证可读的稳定路径(a 的子目录)中。该路径将是 user.home

标签: java file filenotfoundexception ioexception


【解决方案1】:

您需要捕获并处理引发的异常,例如...

public void actionPerformed(ActionEvent arg0) {

    String sLine;

    Vector<Score> scoreVec = new Vector<Score>();

    //Here I am getting a FileNotFoundException for (new FileReader("scores.txt")
    try (BufferedReader in = new BufferedReader(new FileReader("scores.txt"))) {

        //Here I am getting an IOException for in.readLine()
        while ((sLine = in.readLine()) != null) {
            scoreVec.addElement(new Score(sLine));
        }

    } catch (IOException exp) {
        exp.printStackTrace();
    }

    //Placeholders until I get the rest of the program working
    System.out.println(scoreVec.get(1).name);
    System.out.println(scoreVec.get(1).country);
}

请参阅Exceptions trailThe try-with-resources Statement 了解更多详情

【讨论】:

    【解决方案2】:

    相关类和scores.txt的真实路径是什么

    我不推荐,但只有一个可以使用 score.txt 文件的完整路径。

    【讨论】:

    • scores.txt 是 src 文件夹上方的一个文件夹(所以我猜是主项目文件夹?)
    • 相对路径很好,让程序更灵活,但你需要注意程序的执行位置会如何变化
    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多