【问题标题】:FileNotFoundException catch error when reading from file in Java从 Java 中读取文件时,FileNotFoundException 捕获错误
【发布时间】:2013-02-17 06:04:42
【问题描述】:

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

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

【问题讨论】:

    标签: java file input output


    【解决方案1】:

    Java 中的作用域是基于块的。您在块内声明的任何变量都只在同一块结束之前的范围内。

    try 
    { // start try block
        File file = ...;
    
    } // end try block
    catch (...) 
    { // start catch block
    
      // file is out of scope!
    
    } // end catch block
    

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

    File file = ...;
    
    try 
    { // start try block
    
    
    } // end try block
    catch (...) 
    { // start catch block
    
      // file is in scope!
    
    } // end catch block
    

    【讨论】:

    • 好的,有道理。这第一部分实际上是由教授给出的,所以我想我只需要画一个箭头来移动 try 块上方的线。我不确定这是一个错误还是我们应该抓住它。谢谢!
    【解决方案2】:

    file 变量在try 块中声明。它超出了catch 块的范围。 (尽管在这种情况下不可能发生,想象一下如果在执行甚至到达变量声明之前抛出异常。基本上,您无法访问在相应的 try 中声明的 catch 块中的变量块。)

    您应该在 try 块之前声明它:

    File file = new File("input1.txt");
    try
    {
        ...
    }
    catch(FileNotFoundException exception)
    {
        System.out.println("The file " + file.getPath() + " was not found.");
    }
    catch(IOException exception)
    {
        System.out.println(exception);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多