java.io.FileNotFoundException - file DOES exist in directory

Joe Morgan picture Joe Morgan · Jan 9, 2015 · Viewed 9.7k times · Source

I keep receiving the same error whilst trying to read a file. The file DOES exist in the directory, what am I doing wrong?

package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class MenuSample{

    public static void main(String[] args) {

        File f = new File("C:/Users/Joe/Documents/workspace/ArtificialLifeFX/res/latest.txt");

        Scanner scanner = null;
        try {
            scanner = new Scanner(f);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        scanner.useDelimiter("\r\n");
    }
}

I get the following error:

java.io.FileNotFoundException: C:\Users\Joe\Documents\workspace\ArtificialLifeFX\res\latest.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.util.Scanner.<init>(Unknown Source)
    at test.MenuSample.main(MenuSample.java:16)
Exception in thread "main" java.lang.NullPointerException
    at test.MenuSample.main(MenuSample.java:21)

Forgive me if I'm being naive, I'm new to java. I'm running Eclipse Luna on Windows 7.

Answer

duffymo picture duffymo · Jan 9, 2015

Believe the JVM when it tells you such things. There's no sense insisting you're correct; you can't win that argument. You need to figure out what you've done wrong.

My suggestion? Try this:

    File f = new File("C:\\Users\\Joe\\Documents\\workspace\\ArtificialLifeFX\\res\\latest.txt");

On my Windows 7 machine it would be:

    File f = new File("C:\\Users\\Joe\\My Documents\\workspace\\ArtificialLifeFX\\res\\latest.txt");

Check your path to make sure it's absolutely spot on.