繁体   English   中英

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

[英]How do I fix a FileNotFoundException when the program throws an IOException?

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

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

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

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

如果您想知道它在哪里寻找文件,可以将System.out.print(infile.getAbsolutePath());放进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);
}

暂无
暂无

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

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