简体   繁体   English

为什么我找不到我的文件?

[英]Why can't I find my File?

I'm trying to open a CSV file name "logger.csv" which I have saved in the source folder itself.我正在尝试打开一个保存在源文件夹中的 CSV 文件名“logger.csv”。

public static void main(String[] args) {
    String filename = "logger.csv";
    File motor_readings = new File(filename);
    try {
        Scanner inputStream = new Scanner(motor_readings);
        while (inputStream.hasNext()){
            System.out.println(inputStream.next());
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        System.out.println("Error: File not found!");
    }
}

However, this keeps on giving me a "File not found" error.但是,这一直给我一个“找不到文件”错误。

If you use relative pathing as you are right now - the file needs to exist in the project root, not in the directory of the java file.如果您现在使用相对路径 - 该文件需要存在于项目根目录中,而不是在 java 文件的目录中。

Consider this hierarchy:考虑这个层次结构:

project/
  src/main/java
    file.java
    logger.csv

new File("logger.csv") will not work. new File("logger.csv")将不起作用。

project/
  logger.csv
  src/main/java
    file.java

new File("logger.csv") will now work. new File("logger.csv")现在可以工作了。 (notice, the file is adjacent to the src directory.) (请注意,该文件与 src 目录相邻。)

Put the file on level up.将文件放在级别上。 In the main folder of the project.在项目的主文件夹中。

To see where the file is expected update the code in your catch clause to:要查看文件的预期位置,请将 catch 子句中的代码更新为:

        System.out.println("Error: File not found: " + motor_readings.getAbsolutePath());

Put it there and be sure to refresh your workspace in Eclipse so that the file can be seen.将它放在那里并确保在 Eclipse 中刷新您的工作区,以便可以看到该文件。

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

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