Ryk
Ryk

Reputation: 133

File not found java

I have a problem when reading a text file in java. The class is FlashCardReader and I have the following constructor that handles the part of the reading.

public FlashCardReader( String fileName ) {
    try{

        reader = new BufferedReader(new FileReader(fileName));

    }catch(FileNotFoundException e){
        System.out.println("The file was not found or the name may be wrong!");
    }
}

My main method looks like this:

public static void main(String[] args) {
    FlashCardReader fcr = new FlashCardReader("Questions.txt");
}

And the final output is: The file was not found or the name may be wrong!

enter image description here

Some help would be greatly appreciated, cheers!

Upvotes: 1

Views: 474

Answers (1)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can print the current directory of your java program where it is executed from with this java code,

System.out.println("CurrentDir: " + (new File(".").getCanonicalPath()));

Say it prints,

CurrentDir: D:\pkr\test

Then you can correctly choose a path through which your file can be correctly located.

Most likely, your src folder should be in test directory and in that case you can either move your file from src folder to test folder or refer your file in your code like this,

..\\Questions.txt

which should be able to read your file.

Let me know if this works.

Upvotes: 2

Related Questions