繁体   English   中英

找不到文本文件引发异常

[英]Text file not found throwing exception

我确定确实缺少一些愚蠢的东西,但是由于某种原因,即使我的input.txt文件位于软件包中,也会出现“未处理的异常类型FileNotFoundException”错误。 任何帮助将是巨大的!

扫描仪代码:

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();
      }
    }
  }    
}

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

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

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

由于您是在static方法中执行此代码的,因此将getClass替换为ClassName.class

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM