简体   繁体   English

如何从 Java 中 Main 类的相对路径读取文件?

[英]How can I read a file from a path relative of my Main class in Java?

On the same directory of my Main.java file, I have a package/folder named database , and inside the database package I have a file named Data.txt .Main.java文件的同一目录中,我有一个名为database的包/文件夹,在数据库包中我有一个名为Data.txt的文件。

This is my code of Main.java , but it is throwing this error:这是我的Main.java代码,但它抛出了这个错误:

java: exception java.io.FileNotFoundException java: 异常 java.io.FileNotFoundException

How can I get the file from a relative file?如何从相对文件中获取文件? I'm used to web development, and usually something with a .我习惯于 Web 开发,通常使用 . dot like "./folder/file.txt" works.“./folder/file.txt”这样的点有效。

import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;

    public class Main {

        public static void main(String[] args) {

            readFile();

        }

        public static void readFile() {

            File file = new File("./database/Data.txt");
            Scanner scanner = new Scanner(file);

            try {

                while (scanner.hasNextLine()) {
                    int i = scanner.nextInt();
                    System.out.println(i);
                }
                scanner.close();
            }
            catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }

    }

You are not importing FileNotFoundException class. 您没有导入FileNotFoundException类。 also, scanner statement throws the exception which should inside try. 同样,扫描器语句会抛出应在try内的异常。 Solution is as below. 解决方法如下。

import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;

public class Main {

    public static void main(String[] args) {

        readFile();

    }

    public static void readFile() {

        File file = new File("database/Data.txt");

        try {
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                int i = scanner.nextInt();
                System.out.println(i);
            }
            scanner.close();
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

}

Only check if those content can read using scanner or not. 仅检查那些内容是否可以使用扫描仪读取。 Content having int properly. 内容具有正确的int。 otherwise it will throw java.util.InputMismatchException. 否则将抛出java.util.InputMismatchException。

Are you working on a mac or windows system.你是在mac还是windows系统上工作。 I am on windows and ".\database\Data.txt" would most probably work depending on where the file is in your file structure.我在 Windows 上,“.\database\Data.txt”很可能会根据文件在文件结构中的位置工作。

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

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