使用try / catch后出现空指针异常

时间:2014-06-24 23:24:02

标签: java

仍在处理同一个程序。我虽然在另一个线程中的建议之后差不多完成了我实现了一个运行良好的try / catch语句但是我现在得到了一个 "在线程中的异常" main&#34 ; SimpleJavaAssignment.Company.main(Company.java:31)"

的java.lang.NullPointerException

触发异常的代码:

File file = new File(Company.class.getResource("input.txt").getFile());

完整代码:

package SimpleJavaAssignment;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class Company
{
  ArrayList<Department> deptList = new ArrayList<Department>();

  public Department checkDepartment(String name)
  {
    for(Department dept: deptList)
    {
      if(dept.getName().equals(name))
      {
      return dept;
      }
    }
    Department d = new Department(name);
    deptList.add(d);
    return d;
  }

  public static void main(String[] args)
  {

    System.out.println ("This program will compile and display the stored employee data.");

    Scanner inputFile = null;
    File file = new File(Company.class.getResource("input.txt").getFile());


    try {

        inputFile = new Scanner(file);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Company c = new Company();
    String input = inputFile.nextLine();



    while(inputFile.hasNextLine() && input.length() != 0)
    {

      String[] inputArray = input.split(" ");
      Department d = c.checkDepartment(inputArray[3]);
      d.newEmployee(Integer.parseInt(inputArray[2]), inputArray[0] + " " + inputArray[1], d);
      input = inputFile.nextLine();
    }

    System.out.printf("%-15s %-15s %-15s %-15s %n", "DEPARTMENT", "EMPLOYEE NAME", "EMPLOYEE AGE",
          "IS THE AGE A PRIME");
    for(Department dept:c.deptList)
    {
      ArrayList<Employee> empList = dept.getEmployees();
      for(Employee emp: empList)
      {
      emp.printInfo();
      }
    }
  }    
}

1 个答案:

答案 0 :(得分:4)

当您调用Company.class.getResource("input.txt")

您使用的是相对资源名称,该名称是相对于该类的程序包处理的。那么,您确定在input.txt包的同一级别有一个名为SimpleJavaAssignment的文件吗?

您也可以指定文件的绝对路径并将其传递到File构造函数中,如下所示:

File file = new File("/my/path/input.txt");