Question

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!

Was it helpful?

Solution

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"));

OTHER TIPS

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(); 
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top