File not found java

限于喜欢 提交于 2021-02-05 09:01:41

问题


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!

Some help would be greatly appreciated, cheers!


回答1:


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.



来源:https://stackoverflow.com/questions/53526135/file-not-found-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!