Adding .txt file as a resource Java

1.3k views Asked by At

I have a .txt file and a image in a file called res. I added in the file to my path as well. I did the code bellow and it works in my Eclipse IDE just fine. When exporting a jar and running it, it does nothing. Running the jar with cmd says the class path can not be found. SO I tried the second chunk of code with no success. My image that is there works fine. bgi = new ImageIcon(getClass().getResource("bg.png"));

Scanner s = null;
        try {
            s = new Scanner(new File("res//10kaddress.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ArrayList<String> paddress = new ArrayList<String>();
        while (s.hasNext()){
            paddress.add(s.next());
        }
        s.close();

So I tried doing this below and no mater what I do it will not read the txt file

URL url = GUI.class.getResource("10kaddress.txt");
    File ff = new File(url.getPath());


    Scanner s = null;
    try {
        s = new Scanner(ff);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    ArrayList<String> paddress = new ArrayList<String>();
    while (s.hasNext()){
        paddress.add(s.next());
    }
    s.close();

and get this error

java.io.FileNotFoundException: C:\Users\Major%20Lee\Sketch\GUI\res\10kaddress.txt (The system cannot find the path specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.util.Scanner.<init>(Unknown Source)
    at GUI.main(GUI.java:68)
Exception in thread "main" java.lang.NullPointerException
    at GUI.main(GUI.java:73)

Any help would be great. Thanks!

2

There are 2 answers

0
Elliott Frisch On BEST ANSWER

I would open it as a ResourceStream (or I would just use a ResourceBundle), that is like this -

InputStream is = getClass().getResourceAsStream("10kaddress.txt");
Scanner s = new Scanner(is);
1
An SO User On

When you have a file embedded in a JAR, you need to use the getResourceAsStream(), as it has been pointed out.

Also, I suspect that there is a problem in your path. From the error I can see that you are on a Windows machine. Your path is :

res//10kaddress.txt  

When escaping the separators, use a / (single forward slash) or a \\( double backslash). The backslash has another backslash with it and is hence called as being escaped. Try changing the path and see if that works for you.

So, make your path as:

res/10kaddress.txt   

Double-check manually to see if the file is at the path specified.