Bob
Bob

Reputation: 51

Reading file error: File Not Found

I have the follwing

 Scanner scanner = new Scanner(new File("hello.txt"));
   while(scanner.hasNextInt()){
       int i = scanner.nextInt();
       System.out.println(i);
    }

Why do I get an error when I run it? It says file not found (The system cannot find the files specificed) in java.io.fileinputstream. But the file does exist.

Upvotes: 0

Views: 13068

Answers (3)

Mya
Mya

Reputation: 1

Make sure your file is in the project directory at the first level. Not in src, class, etc. but just straight in the project directory.

Upvotes: 0

Steve Perkins
Steve Perkins

Reputation: 11880

As has been pointed out, you could solve the problem by specifying an absolute path. However, you actually DO have some control over the current working directory from within the Java code. If the file you're reading is in the current working directory, then you could use this:

Scanner scanner = new Scanner(
    new File(System.getProperty("user.dir") + File.separatorChar +"hello.txt"));

The "user.dir" system level property contains the directory from which your application is running. Note that this ISN'T necessarily the directory in which the ".class" file resides. If that's what you're wanting, then the best approach would be loading it as a classpath resource (well covered in another answer.)

Upvotes: 0

BalusC
BalusC

Reputation: 1109655

You need to specify an absolute path. Right now you're specifying a relative path. The path is relative to the current working directory over which you have no control from inside the Java code. The relative path depends on how you're executing the Java code. In command prompt, it's the currently opened folder. In an IDE like Eclipse, it's the project's root folder. In a webapplication, it's the Server's binary folder, etc.

Scanner scanner = new Scanner(new File("/full/path/to/hello.txt"));

In a Windows environment, the above example equals to C:\full\path\to\hello.txt.


If your actual intent is to place this file in the same folder of the currently running class, then you should be obtaining it as a classpath resource:

Scanner scanner = new Scanner(getClass().getResouceAsStream("hello.txt"));

Or if you're inside the static context:

Scanner scanner = new Scanner(YourClass.class.getResouceAsStream("hello.txt"));

Where YourClass is the class in question.

Upvotes: 5

Related Questions