Problem with relative file path

后端 未结 6 1905
旧时难觅i
旧时难觅i 2021-01-01 22:31

So here is my program, which works ok:

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import         


        
相关标签:
6条回答
  • 2021-01-01 23:05

    It must be a FileNotFoundException causing NPE in the finally block. Eclipse, by default, executes the class with the project folder (D:/java-projects/HelloWorld in your case ) as the working directory. Put the usnumbers.txt file in that folder and try. Or change the working directory in Run Configuration -> Argument tab

    0 讨论(0)
  • 2021-01-01 23:08

    The NullPointerException is due to the fact that new FileReader() expression is throwing a FileNotFoundException, and the variable s is never re-assigned a non-null value.

    The file "usnumbers.txt" is not found because relative paths are resolved (as with all programs) relative to the current working directory, not one of the many entries on the classpath.

    To fix the first problem, never assign a meaningless null value just to hush the compiler warnings about unassigned variables. Use a pattern like this:

    FileReader r = new FileReader(path);
    try {
      Scanner s = new Scanner(new BufferedReader(r));
      ...
    } finally {
      r.close();
    }
    

    For the second problem, change directories to the directory that contains "usnumbers.txt" before launching java. Or, move that file to the directory from which java is run.

    0 讨论(0)
  • 2021-01-01 23:18

    In Eclipse, you can also look under "Run Configurations->Than TAB "Classpath".

    By default the absolut path is listed under "User Entries" in [icon] 'your.path' (default classpath)

    0 讨论(0)
  • 2021-01-01 23:20

    Since your working directory is “D:/java-projects/HelloWorld”

    @pdbartlett's id is great, But String filePath = new File(".").getAbsolutePath() will output "D:/java-projects/HelloWorld/." which is not easy to add your extra relative path like "filePath" + "/src/main/resources/" + FILENAME which located in resources folder.

    I suggest with String filePath = new File("").getAbsolutePath() which return the project root folder

    0 讨论(0)
  • 2021-01-01 23:21

    From which directory is the class file executed? (That would be the current working directory and base directory for relative paths.)

    If you simply launch the application from eclipse, the project directory will be the working directory, and you should in that case use "bin/usnumbers.txt".

    0 讨论(0)
  • 2021-01-01 23:24

    If aioobe@'s suggestion doesn't work for you, and you need to find out which directory the app is running from, try logging the following:

    new File(".").getAbsolutePath()
    
    0 讨论(0)
提交回复
热议问题