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

问题描述 投票:0回答:2

我正在做一个编程任务,涉及从包含员工数据的文件中读取,并且需要编写一个抛出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。

java file filenotfoundexception
2个回答
1
投票

你需要从Project的root文件夹中提供文件路径,所以如果你的文件在src下,那么路径将是:src/employeeData.txt


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);
}
© www.soinside.com 2019 - 2024. All rights reserved.