FileNotFoundException although the file is exist

1.2k views Asked by At

I'm trying to get to some text file in my computer but I keep getting this exception although the path is correct and the file is exist. Here is my code:

    public static void main(String[] args) throws IOException {

    File wordFile = new File("‪D:\\IDC\\Stuff\\wordList.txt");
    RandomAccessFile wordsList = new RandomAccessFile(wordFile, "rw");

    System.out.println(wordFile.exists());


}

The error:

Exception in thread "main" java.io.FileNotFoundException: ‪D:\IDC\Stuff\wordList.txt (The filename, directory name, or volume label syntax is incorrect)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:243)
at WordChecker.main(WordChecker.java:12)
2

There are 2 answers

0
codedabbler On

Can you rename the file? This can help if you copied the file name from another location and it had non-visible characters in it.

1
Bacteria On

When I copied your code and tried to save it in Eclipse. I got the below error

enter image description here

I concluded from this, although your path looks '‪D:\\IDC\\Stuff\\wordList.txt' but actually it is not.So what I did, just type this line File file =new File("D:\\IDC\\Stuff\\wordList.txt"); instead of copy it from your code. And it worked. It seems you also copied it from somewhere and for encoding issue you are getting the problem.

One more point, you should use System.getProperty("file.separator") instead of \\ or / just like below

File wordFile = new File("‪D:" + System.getProperty("file.separator")
                + "IDC" + System.getProperty("file.separator") + "Stuff"
                + System.getProperty("file.separator") + "wordList.txt");

file.separator

Character that separates components of a file path. This is "/" on UNIX and "\" on Windows.