Hack-R Hack-R - 2 months ago 6
Java Question

File not found for file in src\resources accessed with ClassLoader.getSystemResource("file.txt")

I am trying to access a text file within my Java Netbeans project, but I keep getting file not found.

Please note that I've tried specifying the file with "src\ ....", "resources\ ...", and only using the file name.

This is my code:

static class Task extends TimerTask {
// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource("word_list_moby_credits.txt");
// Turn the resource into a File
File f = new File(dir_url.getFile());

Scanner scanner = new Scanner(f);


I'm getting


File not found


on the last line of the code above.

This is my project:

enter image description here

enter image description here

Answer

Please try this to read words.txt in {Source Packages}/resources:

public static void main(String[] args) {
    try{
        URL url = Task.class.getResource("/resources/words.txt");
        Scanner scanner = new Scanner(url.openStream());
        System.out.println("" + scanner.next());
    } catch(IOException ex) {
        ex.printStackTrace();
    }
}

In case you already have other main method and still want to keep this code outside a method, you can wrap it in a static block:

static class Task extends TimerTask {
   static {
        try {
            URL url = Task.class.getResource("/resources/words.txt");
            Scanner scanner = new Scanner(url.openStream());
            System.out.println("" + scanner.next());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
   }
}