2

I have a need to generate complicated text files from a Java desktop application.

I've decided the code would be considerably easier to implement if I could copy a template file and tailor it to whatever needs to be constructed.

I will only be distributing a jar to the customers. Is there a best-practice on how to handle this?

  • Is it even possible to copy a resource from the jar at runtime?
  • Is it better to "auto-generate" a template on first execution of the jar?
Nate
  • 18,892
  • 27
  • 70
  • 93
  • I don't understand where from you want to copy the file. Can you make it a bit clearer? Where is template file? Is it in jar? Do you want customers to have this file on their machine after launching application? – amorfis Jul 21 '09 at 20:16
  • possible duplicate of [How to copy file inside jar to outside the jar?](http://stackoverflow.com/questions/10308221/how-to-copy-file-inside-jar-to-outside-the-jar) – David Moles May 19 '14 at 18:39

2 Answers2

8

You can read a file stored in your jar using:

Class.getResourceAsStream(pathToFile);

See this question for details.

Community
  • 1
  • 1
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
5

Yes, you can read a resource from your JAR and write it to your file system. As kgiannakakis suggests, you'll want to get resource as stream.

However, which classloader to use is murky. I've often seen suggestions that in web applications you should use the context classloader:

Thread.currentThread().getContextClassLoader().getResourceAsStream() 

But then on a quick search to confirm this was still the correct advice, a lot of people recommend the current class loader instead of the context class loader, although most people acknowledge there's no answer that will work perfectly in every situation. Whee!

At this point I'd say just use the current class loader as @kgiannakakis suggested -- it's simpler, and it's not clear that using the context class loader will be any better. If you encounter a scenario where that doesn't work, maybe try the context class loader as an alternative.

Geoffrey Wiseman
  • 5,459
  • 3
  • 34
  • 52