I am using Java.util.zip to add some configuration resources into a jar file. When I call Addfiletozip () method It overwrites the jar completely, instead of adding the file to the jar. Why I need to write the config to the jar is completely irrelevant. And I do not wish to use any external API ' s.
Edit:the jar is not running in the VM and Org.cfg.resource are the package I ' m trying to save the file to, the file is a s Tandard text document and the jar being edited contains the proper information before this method is used.
My Code:
Public voidaddfiletozip (file filetoadd, file ZipFile) {Zipoutputstream Zos=NULL; FileInputStream FIS=NULL; ZipEntry ze=NULL; byte[] buffer =NULL; intLen; Try{Zos=NewZipoutputstream (NewFileOutputStream (ZipFile)); } Catch(FileNotFoundException e) {} ze=NewZipEntry ("org" + file.separator + "cfg" +File.separator+ "Resource" + File.separator +filetoadd.getname ()); Try{zos.putnextentry (ze); FIS=NewFileInputStream (Filetoadd); Buffer=New byte[(int) Filetoadd.length ()]; while(len = fis.read (buffer)) > 0) {zos.write (buffer,0, Len); } } Catch(IOException e) {}Try{Zos.flush (); Zos.close (); Fis.close (); } Catch(IOException e) {}}
The code you showed overrides a file no matter if it would is a zip file or not. Does not care about ZipOutputStream
existing data. Neither any stream oriented API does.
I would recommend
Create new file using ZipOutputStream
.
Open existing withZipInputStream
Copy existing entries to new file.
ADD new entries.
Replace old file with a new one.
Hopefully in Java 7 we got Zip File System.
We can directly write to files inside Zip files
New Hashmap<> (); Env.put ("Create", "true"= Paths.get ("test.zip"= Uri.create ("jar:" + Path.touri ()); Try (FileSystem fs = Filesystems.newfilesystem (URI, env)) { = Fs.getpath ("New.txt"); Try (writer writer = Files.newbufferedwriter (NF, standardcharsets.utf_8, standardopenoption.create)) { Writer.write ("Hello");} }
Http://stackoverflow.com/questions/17500856/java-util-zip-adding-a-new-file-overwrites-entire-jar?lq=1
Java.util.zip Adding a new file overwrites entire jar? Go