未找到文本文件抛出异常

时间:2014-06-24 22:47:01

标签: java arrays

我确信我遗漏了一些非常愚蠢的东西,但由于某种原因我收到了“未处理的异常类型FileNotFoundException”错误,即使我的input.txt文件位于包中。任何帮助都会很棒!

扫描仪代码:

File file = new File("input.txt");
Scanner inputFile = new Scanner(file);
Company c = new Company();
String input = inputFile.nextLine();

完整的课程代码:

package SimpleJavaAssignment;

import java.io.File;
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.");


    File file = new File("input.txt");
    Scanner inputFile = new Scanner(file);
    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();
      }
    }
  }    
}

2 个答案:

答案 0 :(得分:2)

您的主要问题与您查找文件的正确位置或错误位置无关(尽管以后可能会出现问题),目前的问题是您没有处理编译器的异常抱怨。在读取文件并将其与扫描程序一起使用时,您需要将抛出异常的代码放在try / catch块中,或让您的方法抛出异常。如果您还没有阅读exception tutorial,请自己和我们一起帮忙看看吧。

答案 1 :(得分:1)

new File("input.txt");将在正在执行的jar的相同位置寻找文件。由于您声明该文件位于该类的同一个包中,因此您应使用返回URL的{​​{3}}。然后,调用Class#getResource以检索具有文件完整路径的String。

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

由于您使用static方法执行此代码,请将getClass替换为ClassName.class

File file = new File(Company.class.getResource("input.txt").getFile());
相关问题