从Java中的文件读取时,FileNotFoundException捕获错误

时间:2013-03-02 21:41:23

标签: java file input output

我正在尝试编写一个简单的程序,从文本文件中读取整数,然后将总和输出到输出文件。我得到的唯一错误是在第38行的catch块中“未解决的编译问题:文件无法解析”。请注意,“file”是我的输入文件对象的名称。如果我注释掉这个异常块,程序运行正常。任何建议将不胜感激!

import java.io.*;
import java.util.Scanner;

public class ReadWriteTextFileExample 
{
    public static void main(String[] args) 
    {
        int num, sum = 0;

        try
        {
            //Create a File object from input1.txt
            File file = new File("input1.txt");
            Scanner input = new Scanner(file);

            while(input.hasNext())
            {
            //read one integer from input1.txt
                num = input.nextInt();
                sum += num;
            }
            input.close();  

        //create a text file object which you will write the output to
        File output1 = new File("output1.txt");
        //check whether the file's name already exists in the current directory
        if(output1.exists())
        {
            System.out.println("File already exists");
            System.exit(0);
        }
        PrintWriter pw = new PrintWriter(output1);
        pw.println("The sum is " + sum);
        pw.close();
    }
    catch(FileNotFoundException exception)
    {
        System.out.println("The file " + file.getPath() + " was not found.");
    }
    catch(IOException exception)
    {
        System.out.println(exception);
    }
}//end main method
}//end ReadWriteTextFileExample

2 个答案:

答案 0 :(得分:4)

file变量在try块中声明。它超出catch块的范围。 (虽然在这种情况下不可能发生,但想象一下如果在执行甚至到达变量声明之前抛出了异常。基本上,你不能访问在catch块中的变量,该变量在相应的{{ {1}}阻止。)

你应该在 try块之前声明它

try

答案 1 :(得分:3)

Java中的范围基于块。您在块中声明的任何变量仅在范围内,直到同一块的结尾。

try 
{ // start try block
    File file = ...;

} // end try block
catch (...) 
{ // start catch block

  // file is out of scope!

} // end catch block

但是,如果您在file阻止之前声明try,它将保留在范围内:

File file = ...;

try 
{ // start try block


} // end try block
catch (...) 
{ // start catch block

  // file is in scope!

} // end catch block