• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to load a file in jar file  RSS feed

 
pkinuk Buler
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I want to read a file in the root file of the jar file. The code is listed as following. The method I used is the create an File object to generate the instance of InputStream.

The content of the text file:





It worked perfectly when I run it in Eclipse, but it didn't work in a jar file. It threw a IOException when I run the jar file. I have already included the test.txt file in the root path of jar file. I know I can make it work just copy another test.txt file and put it in the same directory with the jar file so that the jar file can read the file. But my purpose is I don't want every user to have a copy of test.txt and put it in the same path with jar file. Anyone can help?

Thank you in advance.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to load as a resource, not as a file.
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or replace the first line with this:
That is, if the file is located in the root of your JAR file. If it's located in the same folder as your class file simply use getClass().getResourceAsStream("test.txt").
 
pkinuk Buler
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I tried the , it worked when I run the jar file. However, it threw a NullPointerException when I run it in Eclipse.


Do you know why it doesn't work? I have included the test.txt file in the project root path.

Thank you in advance.
 
pkinuk Buler
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please ignore what I said, it worked. Thank you very much for both of you.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!