未找到java文本文件引发异常
我确信我遗漏了一些非常愚蠢的东西,但由于某种原因,即使我输入的是未处理的异常类型FileNotFoundException,我也会收到一个“Unhandled exception type FileNotFoundException”错误。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();
}
}
}
}
# 1 楼答案
您的主要问题与您查找文件的正确或错误位置无关(尽管这可能是以后的问题),您当前的问题是您没有处理编译器抱怨的异常。在读取文件并将其与扫描仪一起使用时,您需要将引发异常的代码放入try/catch块中,或者让您的方法引发异常。如果你还没有读过exception tutorial,请帮你自己和我们一个忙,读一读
# 2 楼答案
new File("input.txt");
将在正在执行的jar的相同位置查找文件。由于您声明文件在类的同一个包中,因此应该使用返回URL
的^{由于您是在
static
方法中执行此代码,因此将getClass
替换为ClassName.class
: