Problem with relative file path

后端 未结 6 1925
旧时难觅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: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.

提交回复
热议问题