2

I have a file I'm storing within my jar that I use a default setting file. I wish to write this file out to a user defined path. How do I write it out? This file that I'm trying to write out is in the same location as my class files that will be writing this file

stackoverflow
  • 18,348
  • 50
  • 129
  • 196
  • I am not sure if you can write to the class file location if the class is packaged within the jar. – Kalpak Gadre Apr 23 '12 at 15:06
  • *"default setting file"* Attribute+value pairs are well stored as [`Properties`](http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html). What form are these preferences in? – Andrew Thompson Apr 23 '12 at 16:01

3 Answers3

4

Use getResourceAsStream to access the resource. Create a FileOutputStream for the file you wish to write. Read from one stream and write to the other. Preferably, use buffering, and don't forget to close your streams when you're done.

See Location-Independent Access to Resources.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
2

use "getResourceAsStream"

-> http://mindprod.com/jgloss/getresourceasstream.html

Thkru
  • 4,218
  • 2
  • 18
  • 37
1

given a resource that you want to write to a given Path path, then you can use:

try(InputStream is = this.getClass().getResourceAsStream(resource)){
    Files.copy(is, path);
} catch (Exception e){
    throw new RuntimeException(e);
}
arcuri82
  • 885
  • 1
  • 8
  • 17