程序抛出IOException时如何修复FileNotFoundException?

时间:2019-04-11 15:34:55

标签: java file filenotfoundexception

我正在做一个编程任务,其中涉及从包含员工数据的文件中读取数据,并且需要编写一个引发IOException的程序。当我尝试从与我正在编写的Java文件位于同一文件夹中的文件读取文件时,它给了我FileNotFoundException。到目前为止,这是我的代码:

import java.util.*;
import java.io.*;
public class main {
    public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    Employee[] employees = new Employee[19];
    File infile = new File("employeeData.txt");
    Scanner inputFile = new Scanner (infile); // FileNotFoundException 
    //  thrown here
}

文本文件employeeData.txt的前几行,该文件与我的main.java文件位于同一文件夹中:

// Type of employee; name; ID
Hourly;Adam White;200156;12.75;40 // then pay rate; hours
Salaried;Allan Westley;435128;38500.00 // then annual salary
Supervisor;Annette Turner;149200;75000.00;5000;435128 614438 435116 548394 // then salary; bonus; ID's of employees who report to her

我希望它会读取上面预览的文本文件,因为它位于同一文件夹中,但是它给了我FileNotFoundException。

2 个答案:

答案 0 :(得分:1)

您需要提供来自Project的root文件夹的文件路径,因此,如果您的文件位于src下,则该路径为:src/employeeData.txt

答案 1 :(得分:0)

发生这种情况是因为JVM试图在当前工作目录中查找您的文件,该目录通常是项目的根文件夹,而不是src文件夹。

您可以调整文件的相对路径以反映该路径,也可以提供绝对路径。

如果您想知道它在哪里寻找文件,可以在创建System.out.print(infile.getAbsolutePath());对象之后放置File

具有相对路径的解决方案:

 public static void main(String[] args) throws IOException 
 {
    Employee[] employees = new Employee[19];
    File infile = new File("src/employeeData.txt");
    Scanner inputFile = new Scanner(infile);
 }

具有绝对路径的解决方案:

public static void main(String[] args) throws IOException 
{
    Employee[] employees = new Employee[19];
    File infile = new File("C:/PATH_TO_FILE/employeeData.txt");
    Scanner inputFile = new Scanner(infile);
}
相关问题