有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

需要Java IntelliJ帮助才能不读取我的文件吗

我的Java项目无法读取与我的类位于同一目录中的文件,我需要一些帮助。以下是片段:

private static final String FILENAME = "my_address.txt";

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    AddressBook book = new AddressBook();
    book.readFile(FILENAME);
    int choice;
    do...

每当我尝试输入我的文本文件(my_address.txt)时,我都会收到此消息

my_address.txt could not be found! Exiting..
Process finished with exit code 0

有人能帮我把文件放到我的项目上吗? In the same file directory

正如有人在评论中提到的,以下是我的通讯录部分的一个片段:

package Animal;

public class AddressBook {
    private ArrayList<Person> people;

public AddressBook()
{
    this.people = new ArrayList<>();
}
public void readFile(String filename)
{
    Scanner fileReader;
    try
    {
        fileReader = new Scanner(new File(filename));
        while(fileReader.hasNextLine())
        {
            String[] data = fileReader.nextLine().trim().split(",");
            String firstName = data[0];
            String lastName = data[1];
            String address = data[2];
            String phone = data[3];
            people.add(new Person(firstName, lastName, address, phone));
        }
        fileReader.close();
    }catch(FileNotFoundException fnfe){
        System.out.println(filename + " could not be found! Exiting..");
        System.exit(0);
    }
}

共 (1) 个答案

  1. # 1 楼答案

    从您问题中链接到的图像来看,您似乎正在使用IntelliJ作为IDE。因此,当您构建java源代码时,请输入文件我的地址。txt被复制到包含已编译类的同一目录中,在您的例子中,该类看起来是Main。所以文件我的地址。txt应与fileMain位于同一目录中。类

    下面的代码行创建文件的路径

    new File(filename)
    

    如果变量filename的值是my_address。txt然后是包含文件我的地址的目录的路径。txt将是working directory。如果您不知道工作目录是什么,下面的[java]代码将为您获取它

    String pathToWorkingDirectory = System.getProperty("user.dir");
    

    您会发现它与包含文件Main的目录不同。类,这就是为什么您得到FileNotFoundException

    在您的情况下,请填写我的地址。txt被称为资源,JDK包含一个用于检索资源的API

    因此,为了修复代码,使其不会抛出FileNotFoundException,请使用API检索资源或移动文件我的\u地址。txt到工作目录

    如果使用API,那么下面的java代码将显示如何创建Scanner来读取文件。注意,我假设类Main与类AddressBook位于同一个包中,根据您问题中的代码,类Animal。顺便说一下,建议遵守java naming conventions,因此包的名称应为animal

    java.net.URL url = Main.class.getResource("my_address.txt");
    if (url != null) {
        try {
            java.net.URI uri = url.toURI(); // throws URISyntaxException
            java.io.File f = new java.io.File(uri);
            java.util.Scanner fileReader = new java.util.Scanner(f); // throws FileNotFoundException
        }
        catch (java.net.URISyntaxException | java.io.FileNotFoundException x) {
            x.printStackTrace();
        }
    }
    else {
        // The file was not found.
    }
    

    上面的代码使用multi catch

    我还建议在代码的catch块中打印stack trace