1

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!

randomizertech
  • 2,309
  • 15
  • 48
  • 85
  • How do you execute the program? From the command-line or from an IDE. Most IDEs have an option to specify the working directory of an application. You would have to put your file there. – Björn Pollex Jun 07 '11 at 13:50
  • Is the file already opened elsewhere (including elsewhere in your code without being closed)? The Javadoc for `java.io.FileReader.FileReader( java.io.File )` states that a `FileNotFoundException` is thrown "if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading." If you're sure the file exists and that it's a regular file, then there must be some reason it can't be opened. Make sure the file's permissions allow for reading as well. – Mike M Jun 07 '11 at 13:55

5 Answers5

6

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
5

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

aioobe
  • 413,195
  • 112
  • 811
  • 826
4

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.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
3

try:

URL url = this.getClass().getResource( "words.txt" );
File file = new File(url.getPath());
oliholz
  • 7,447
  • 2
  • 43
  • 82
2

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.

Vineet Reynolds
  • 76,006
  • 17
  • 150
  • 174