Java says FileNotFoundException but file exists

前端 未结 10 1552
遇见更好的自我
遇见更好的自我 2020-11-22 10:19

I have an assignment for my CS class where it says to read a file with several test scores and asks me to sum and average them. While summing and averaging is easy, I am hav

10条回答
  •  旧巷少年郎
    2020-11-22 10:37

    I recently found interesting case that produces FileNotFoundExeption when file is obviously exists on the disk. In my program I read file path from another text file and create File object:

    //String path was read from file
    System.out.println(path); //file with exactly same visible path exists on disk
    File file = new File(path); 
    System.out.println(file.exists());  //false
    System.out.println(file.canRead());  //false
    FileInputStream fis = new FileInputStream(file);  // FileNotFoundExeption 
    

    The cause of the problem was that the path contained invisible \r\n characters at the end.

    The fix in my case was:

    File file = new File(path.trim()); 
    

    To generalize a bit, the invisible / non-printing characters could have include space or tab characters, and possibly others, and they could have appeared at the beginning of the path, at the end, or embedded in the path. Trim will work in some cases but not all. There are a couple of things that you can help to spot this kind of problem:

    1. Output the pathname with quote characters around it; e.g.

        System.out.println("Check me! '" + path + "'");
      

      and carefully check the output for spaces and line breaks where they shouldn't be.

    2. Use a Java debugger to carefully examine the pathname string, character by character, looking for characters that shouldn't be there. (Also check for homoglyph characters!)

提交回复
热议问题