Scanner throws FileNotFoundException but using bufferedreader and inputstream doesn't?

I am trying to write code for a word guessing game, and it works well when I use bufferedreader and inputstream combined. But when I try it using scanner, it cannot find the file, even though in both instances the file is in the same folder. It is in a folder called res under the src folder in my project folder(I am coding in eclipse).

import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;

public class WordGen {

    private final String filename = "/res/words.txt";
    File file = new File(filename);
    Scanner input = null;
    private ArrayList<String> list = new ArrayList<>();

    public WordGen() {
        try {
            input = new Scanner(file);

            while (input.hasNextLine()) {
                String w = input.nextLine();
                list.add(w);
            }
        } catch (Exception ex) {
            System.out.println("File not found.");
        }
    }

    public String getword() {
        if (list.isEmpty()) {
            return "NOTHING";
        }
        return list.get((int) (Math.random() * list.size()));
    }
}

public class test {

    public static void main(String[] args) {
        WordGen wordgen = new WordGen();
        System.out.println(wordgen.getword());
    }

}

I tried searching for this problem but couldn't find it here. I am guessing it's a very small error which I cannot figure out. Thanks and regards.

EDIT: Here's the other code that worked(Everything else same as before):

public WordGenerator() 
 {
    try(InputStream input = getClass().getResourceAsStream(fileName);
            BufferedReader bfreader = new BufferedReader(new InputStreamReader(input))) 
    {
        String line = "";
        while ((line = bfreader.readLine()) != null)
            words.add(line);
    }
    catch (Exception e) 
    {
        System.out.println("Couldn't find file");
    }
}
Jon Skeet
people
quotationmark

Scanner is trying to load a file - and you're providing an absolute filename, /res/words.txt.

In order to create an InputStream, you're loading a resource, giving it an absolute resource name, even though you've called the variable fileName:

getClass().getResourceAsStream(fileName)

That works because it can load a resource called /res/words.txt from the classpath, but it's not loading a file with a filename of /res/words.txt.

You could use a filename of res/words.txt, if you run the code from the src directory... or you could just stick to using getResourceAsStream, which is probably a better idea as it doesn't rely on your working directory, and will continue to work even if your code and resources are packaged up into a jar file.

If you really want to use Scanner, you could always use new Scanner(input) - there's a Scanner constructor accepting an InputStream.

people

See more on this question at Stackoverflow