FileNotFoundException异常;错误

时间:2015-12-06 22:30:33

标签: java arrays

我正在编写一个程序,其中多个方法可以访问文件和从文件中读取的对象数组,但我一直收到此错误。

useHamayelSajaEmployee.java:9: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    public static final Scanner scan2 = new Scanner(file); //scanner for reading from file
                                        ^
1 error

这就是代码的外观:

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

public class useHamayelSajaEmployee 
{
    public static final int MAX_EMPLOYEES = 1000;
    public static final HamayelSajaEmployee []emps = new HamayelSajaEmployee[MAX_EMPLOYEES]; 
    public static final File file = new File("empList.txt");
    public static final Scanner scan2 = new Scanner(file); //scanner for reading from file

我的教授不允许我们使用try-catch。有没有其他方法可以在不使用它的情况下绕过这个错误?

谢谢

3 个答案:

答案 0 :(得分:4)

一点研究会告诉您:FileNotFoundException是一个经过检查的例外。您必须将该调用包装在try/catch块中。

public class HamayelSajaEmployee {
    public static final int MAX_EMPLOYEES = 1000;
    public static final HamayelSajaEmployee []emps = new HamayelSajaEmployee[MAX_EMPLOYEES]; 
    public static File file;
    public static Scanner scan2;

    static {
        try {
            file = new File("empList.txt");
            scan2 = new Scanner(file); 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

答案 1 :(得分:0)

也许尝试添加此

try {

    Scanner scan2 = new Scanner(file);

    while (scan2.hasNextLine()) {
        int i = scan2.nextInt();
        System.out.println(i);
    }
    scan2.close();
} 
catch (FileNotFoundException e) {
    e.printStackTrace();
}

否则尝试

catch (Exception e) {
Toast toast = Toast.makeText(this, "File Not Found" , Toast.LENGTH_SHORT);
toast.show();
}

答案 2 :(得分:0)

这是因为对象"文件"当没有名为" empList.txt"。

的现有文件时,它可能为null

要解决此问题,您最好将Scanner行代码移入方法而不是全局变量,并为该方法添加throw异常:

buffering