6

Possible Duplicate:
Java resource as file

I am kind of new to Java and I am trying to get a text file inside a Jar file.

At the moment when I execute my jar I have to have my text file in the same folder as the jar fil. If the text file is not there I'll get a NullPointerException, which I want to avoid.

What I want to do is to get the txt file inside the jar so I wont have this problem. I tried some guides but they didn't seem to work. My current read function goes like this:

public static HashSet<String> readDictionary()
{
    HashSet<String> toRet = new HashSet<>();
     try
     {
            // Open the file that is the first 
            // command line parameter
            FileInputStream fstream = new FileInputStream("Dictionary.txt");
        try (DataInputStream in = new DataInputStream(fstream)) {
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
            // Read Lines
                toRet.add(strLine);
            }
        }
            return toRet;
     }
     catch (Exception e)
     {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
     } 
     return null;
}
Community
  • 1
  • 1
Nadav
  • 2,589
  • 9
  • 44
  • 63

3 Answers3

7

Don't try to find a file as a "file" in a Jar file. Use resources instead.

Get a reference to the class or class loader and then on the class or class loader call getResourceAsStream(/* resource address */);.


See similar questions below (avoid creating new questions if possible):

Rohit Mistry
  • 113
  • 3
  • 11
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
3
// add a leading slash to indicate 'search from the root of the class-path'
URL urlToDictionary = this.getClass().getResource("/" + "Dictionary.txt");
InputStream stream = urlToDictionary.openStream();

See also this answer.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

Seems like an exact duplicate of this question: How do I access a config file inside the jar?

Further to your problem with NullPointerException, I suggest not to make sure it doesn't happen, but rather prepare for it and handle it properly. I'd go even further to ask you to always check your variables for null value, it's a good thing to do.

Community
  • 1
  • 1
maksimov
  • 5,792
  • 1
  • 30
  • 38