【问题标题】:How do I fix a FileNotFoundException when the program throws an IOException?当程序抛出 IOException 时,如何修复 FileNotFoundException?
【发布时间】:2019-04-11 15:34:54
【问题描述】:

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

【问题讨论】:

  • 尝试将txt文件移动到项目文件夹而不是源文件夹

标签: java file filenotfoundexception


【解决方案1】:

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

【讨论】:

  • 感谢您的帮助!
【解决方案2】:

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

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

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

相对路径的解决方案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-31
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多