从Java中的文件读取时FileNotFoundException捕获错误
问题描述:
我想写一个简单的程序,从文本文件中读取整数,然后将总和输出到输出文件。我得到的唯一错误是在第38行的catch块中“未解决的编译问题:文件无法解析”。请注意,“文件”是我的输入文件对象的名称。如果我注释掉这个异常块,程序运行良好。任何意见,将不胜感激!从Java中的文件读取时FileNotFoundException捕获错误
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
答
范围是基于块的。您在块内声明的任何变量只在该范围内,直到该块的结尾。
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
答
的file
变量在try
块内声明。它在catch
区块范围之外。 (虽然在这种情况下不可能发生,但想象一下,如果在执行之前抛出异常甚至到达变量声明,基本上,您不能访问catch
块中的变量,该块在相应的try
块中声明。)
你应该把它声明之前try块来代替:在Java中
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);
}
好吧,这是有道理的。第一部分实际上是由教授给出的,所以我想我会画一个箭头移动try块上方的一行。我不确定这是否是一个错误,或者我们是否应该抓住它。谢谢! – Johnny 2013-03-02 21:51:42