Win a copy of Create an Uber Clone in 7 Days: Build a real world full stack mobile app in Java this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to load a file in jar file  RSS feed

 
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.
 
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.
 
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this

 
Sheriff
Posts: 21379
92
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.
 
Are you okay? You look a little big. Maybe this tiny ad will help:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!