Why can't I find my File?

懵懂的女人 提交于 2019-12-02 20:19:46

问题


I'm trying to open a CSV file name "logger.csv" which I have saved in the source folder itself.

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.


回答1:


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.

Consider this hierarchy:

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

new File("logger.csv") will not work.

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

new File("logger.csv") will now work. (notice, the file is adjacent to the src directory.)




回答2:


Put the file on level up. In the main folder of the project.




回答3:


To see where the file is expected update the code in your catch clause to:

        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.



来源:https://stackoverflow.com/questions/33446050/why-cant-i-find-my-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!