简体   繁体   中英

Java: How to use Scanner class to read text file in resources folder

在此处输入图片说明

import java.util.*;
import java.io.File;
import java.io.IOException;

public class Test {

    public static void main(String[] args) {
        File source;
        Scanner input;
        String name;
        String id;
        Pokemon x;
        ArrayList<Pokemon> pokelist = null;

        try {
            source = new File("/resources/gen1pokemon.txt");
            input = new Scanner(source);
            input.useDelimiter(",");
            while(input.hasNext()) {
                id = input.next();
                name = input.next();
                x = new Pokemon(id,name);
                pokelist.add(x);

                input.nextLine();
            }
        } catch(Exception e) {
            System.out.println(e);
        }
        System.out.println(pokelist.get(0).getName());
    }
}

I have a text file in my resources folder and I am trying to read that using the Scanner class, however I get an error. java.io.FileNotFoundException: \\resources\\gen1pokemon.txt (The system cannot find the path specified)Exception in thread "main"

Any ideas what could be causing this? I looked around and tried putting "class.getResource("file name")" reference, but I got an error doing that too when declaring file.

Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.

To use the URL in a scanner, get an input stream from it , then use new Scanner(InputStream) .

Have you tried /src/resources/gen1Pokemon.txt ?

Paths can be a bit tricky, try about with different versions depending on the project's structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM