zchholmes
zchholmes

Reputation: 2264

How to use the .txt, .xml and .properties file inside the executable jar?

I have a java project which will read a txt file and process that.

For production purpose, I will need to generate an executable jar which contains this txt file.

I use the code like:

BufferedReader br = new BufferedReader(new FileReader("src/txt_src/sample.txt"));

My jar contains txt_src/sample.txt, but can't use it. Instead, if I put a src directory which has src/txt_src/sample.txt structure, the jar works.

It will be better to generate directly by Eclipse.

Thanks in advance!

Upvotes: 0

Views: 91

Answers (2)

Ingo
Ingo

Reputation: 5381

Put your files in the assets Folder of your Project and use them with:

InputStream stream = null; 
try { 
  stream = getAssets().open("sample.txt"); 
} 
catch (IOException e) { 
   e.printStackTrace(); 
} 

Upvotes: 0

Dodd10x
Dodd10x

Reputation: 3349

Treat the file as a resource and give the path as the package hierarchy.

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29

You can then take the InputStream and wrap it in an InputStreamReader that is wrapped in a BufferedReader. Wrap it in a BufferedInputStream if you need to define the encoding, which you should do.

new BufferedReader(new InputStreamReader(new BufferedInputStream(this.getResourceAsStream("myPackage/myFile.txt")), "UTF-8"));

Upvotes: 2

Related Questions