Help coderanch get a
new server
by contributing to the fundraiser
  • 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

How to locate & write to files inside a Jar

 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,
I have a simple program that reads a string from a file. I want to pack it as a Jar so I need to locate the input file in the following way:



This code works but how can I write to a file located in the same Jar? (the getResourceAsStream returns an InputStream, not the OutputStream that I need).

Thanks in advance,


 
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jars don't have files but rather resources, and you really shouldn't be trying to write into them. Instead perhaps use properties or a datafile external to the Jar.
 
Saloon Keeper
Posts: 15705
367
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I echo that you shouldn't write to a Jar file.

That said, you can. A jar file is simply a zip file with a different extension. You can edit the files in a roundabout way using java.util.zip.*.
 
Sheriff
Posts: 22796
131
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No you can't. Editing into a ZipFile is not supported, not even by the zip protocol itself. If you replace a file inside the zip file, changing the size, you will need to shift data inside the entire zip file.

Most programs that do allow changing files inside a zip file use a shadow copy - upon committing the changes the all contents are put into a new zip file; afterwards the old zip file is replaced by the new one.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic