Including a text file in a jar file and reading it

Possible duplicate:
Java resource as file

I'm kind of new to Java, and I'm trying to get a text file inside a jar file.

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

What I want to do is get the txt file inside the jar, so I won't have this problem. I tried a few guides, but they didn't seem to work. My current read function is as follows:

 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; } 
+6
source share
3 answers

Do not try to find the file as a β€œfile” in the Jar file. Use resources instead.

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


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

+7
source
 // 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 .

+3
source

It seems like an exact duplicate of this question: How to access the configuration file inside the banner?

In addition to your problem with NullPointerException , I suggest that you do not ensure that this does not happen, but rather prepare for it and handle it correctly. I would go even further to ask you to always check variables for a null value, this is good to do.

+2
source

Source: https://habr.com/ru/post/914913/


All Articles