Abel Jojo
Abel Jojo

Reputation: 758

Scanner class java file not found

Scanner Class couldnt find the file I use NetBeansIDE, and the test.txt is in the folder path: D:\netbeans project works\ReadFile\src\readfile\test.txt

in the same folder the readfile.java exsist. the code is as below. It generates file not found.

package readfile;

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


public class ReadFile {

    public static void main(String[] args) throws IOException , FileNotFoundException 
    {  
        Scanner scanner = new Scanner(new File("test.txt"));  

        while (scanner.hasNextLine())  
            System.out.println(scanner.nextLine());  
    }  
}

output:-

run:
Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.util.Scanner.<init>(Scanner.java:636)
    at readfile.ReadFile.main(ReadFile.java:14)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Upvotes: 2

Views: 23049

Answers (6)

fgh
fgh

Reputation: 199

I am aware that this problem has been reported a long time ago, however, I have faced a similar obstacle and then the proposed solutions didn't work, thus I decided to post another answer.

Try using try... catch clause. For instance, only then my code has become compiled by NetBeans.

Upvotes: 0

Sarneet Kaur
Sarneet Kaur

Reputation: 3008

what worked for me was removing .txt extension from the file name and using . to specify current directory (example shown below).

Scanner scanner = new Scanner(new File("./test"));

Upvotes: -1

Ben
Ben

Reputation: 31

Ahhh you aren't specifying the full file path. When a file path is abbreviated (i.e. test.txt), java assumes that the file is in the same directory as the source code that is running it. So either specify the full path, or move the file.

Upvotes: 3

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340993

Add the following before creating Scanner class:

System.out.println(new File("test.txt").getAbsolutePath());

It will show you where JVM expects to find the file and whether it is the folder you expect as well.

Also check file permissions. But most likely it is a problem with default JVM directory.

Upvotes: 8

Ravi Jain
Ravi Jain

Reputation: 1482

The test.txt file should be in the folder where the file readfile.class exists.

Upvotes: 0

Razvan
Razvan

Reputation: 10101

Move it to the ReadFile directory, i.e. the root of the project

Upvotes: 1

Related Questions