获取Java.io.FileNotFoundException;在一个程序中,不知道如何解决

时间:2014-09-05 13:39:58

标签: java exception-handling

自己构建一个小游戏作为一个小项目,我对错误处理等不太好,所以我收到java.io.FileNotFoundException错误,我不确定如何进行。

这是我在这里发表的第一篇文章,所以我为这么模糊而道歉,我猜测我需要抛出异常还是以某种方式捕获它?

import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class GameOver extends Actor {
    public static Counter highScore;
    public static int currentScore;
    /**
     * Act - do whatever the gameOver wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() {
        displayScore();
        if(Greenfoot.isKeyDown("space")) {
            Greenfoot.setWorld(new City());
        }
    } 
    //This is where I am getting the error 
    private void displayScore() {
        highScore = new Counter ("HIGHSCORE: ");
        getWorld().addObject(highScore, 700, 50); //Add width/height
        highScore.setLocation(City.WIDTH/2, City.HEIGHT/4);
        currentScore = (0+City.score);
        int topScore;
        //The error is coming from this block of code
        BufferedReader saveFile = new BufferedReader(new FileReader("TextSave.txt"));
        topScore = Integer.parseInt(saveFile.readLine()); 
        saveFile.readLine();
        saveFile.close();
        if (topScore < currentScore) {
            FileWriter writer = new FileWriter("topScore.txt");
            writer.write(currentScore);
            writer.close();
        }
        highScore.setValue(topScore);
    }
}

4 个答案:

答案 0 :(得分:1)

你的问题是“如何捕捉异常”,这是一个答案:

    //This is where I am getting the error 
    private void displayScore() {
        highScore = new Counter ("HIGHSCORE: ");
        getWorld().addObject(highScore, 700, 50); //Add width/height
        highScore.setLocation(City.WIDTH/2, City.HEIGHT/4);
        currentScore = (0+City.score);
        int topScore;
        try{
          //The error is coming from this block of code
          BufferedReader saveFile = new BufferedReader(new FileReader("TextSave.txt"));
          topScore = Integer.parseInt(saveFile.readLine()); 
          saveFile.readLine();
          saveFile.close();
          if (topScore < currentScore) {
              FileWriter writer = new FileWriter("topScore.txt");
              writer.write(currentScore);
              writer.close();
          }
          highScore.setValue(topScore);
        catch(FileNotFoundException e){
          // Handle your exception here, like print a message 'the file XXX couldn't be read'
        }
    }

或者您可以将它传递给调用函数并在那里处理它:

private void displayScore() throws FileNotFoundException {
   ...
}

答案 1 :(得分:0)

要解决此问题,我有2条建议

  1. 放置文件的完整路径,例如D://my_folder//TextSave.txt
  2. 将文件放在项目的根文件夹中并检查。

答案 2 :(得分:0)

如果你想弄清楚它找不到文件的原因,请把它放在你的代码中:

System.out.println(new File("TextSave.txt").getAbsolutePath());

您将看到它试图打开文件的位置。

如果要正确处理错误,请将IO操作包装在try / catch块中:

try(BufferedReader saveFile = new BufferedReader(new FileReader("TextSave.txt"))) {
    topScore = Integer.parseInt(saveFile.readLine()); 
    saveFile.readLine();
} catch(IOException e) {
    // log the error or show error message here
}

答案 3 :(得分:0)

一种替代的,更强大的方法(仍然涉及错误处理),将为目标文件路径创建一个文件,这将允许您验证文件的存在,如果它实际上是一个可读文件,等,等等。

这将允许您检查文件的状态并抛出您定义的异常,以便在应用程序失败的哪个位置特别明确地确定:

File file = new File(System.getProperty("user.dir")
            + "\\GameName\\Saves\\" + textsave.txt");
if(!f.exists()) {
    f.getParentFile().mkdirs();
    try {
        f.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

然后像以前那样管理你的FileWriter,或者更进一步编写代码来处理读取/写入文件:

// just as an example - not complete, runnable code
BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

FileWriter fw = new FileWriter(file, append); // append is a boolean flag to overwrite/not overwrite the entire content of the file
BufferedWriter bw = new BufferedWriter(fw);
bw.write(currentScore); // using your code

希望这有帮助!可能有点矫枉过正,可能不是:)