Problem with Java FileReader [duplicate]

一世执手 提交于 2019-12-08 04:32:39

问题


Hello I have this in my code

File file = new File("words.txt");
    Scanner scanFile = new Scanner(new FileReader(file));
    ArrayList<String> words = new ArrayList<String>();

    String theWord;    
    while (scanFile.hasNext()){
        theWord = scanFile.next();
        words.add(theWord);
    }

But for some reason I am getting a

java.io.FileNotFoundException

I have the words.txt file in the same folder as all of my .java files

What am I doing wrong? Thanks!


回答1:


Tip: add this line to your code...

System.out.println(file.getAbsolutePath());

Then compare that path with where your file actually is. The problem should be immediately obvious.




回答2:


The file should reside in the directory from which you execute the application, i.e. the working directory.




回答3:


Generally it's a good idea to package data files with your code, but then using java.io.File to read them is a problem, as it's hard to find them. The solution is to use the getResource() methods in java.lang.ClassLoader to open a stream to a file. That way the ClassLoader looks for your files in the location where your code is stored, wherever that may be.




回答4:


try:

URL url = this.getClass().getResource( "words.txt" );
File file = new File(url.getPath());



回答5:


You haven't specified an absolute path. The path would therefore be treated as a path, relative to the current working directory of the process. Usually this is the directory from where you've launched the Main-Class.

If you're unsure about the location of the working directory, you can print it out using the following snippet:

System.out.println(System.getProperty("user.dir"));

Fixing the problem will require adding the necessary directories in the original path, to locate the file.



来源:https://stackoverflow.com/questions/6266188/problem-with-java-filereader

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