• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

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
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: 21557
100
Chrome Eclipse IDE Java Spring Ubuntu VI Editor 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.
 
Shiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!