I created a copy of the tar archive and copied to entire content to it. Then I delete the old tar archive.
Public voidAppendfileintararchive (String Tarpath, String tarfilename, String file2writename, String file2writecontent)throwsauthenticationexception, IOException {if(Tarpath = =NULL|| Tarfilename = =NULL||Tarfilename.isempty ()) {Log.warn ("The path or the name of the TAR archive is null or empty."); return; } FinalFile Tarfile =NewFile (Tarpath, tarfilename); FinalFile Filetoadd =NewFile (Tarpath, file2writename); Fileutils.write (Filetoadd, file2writecontent); if(File2writename = =NULL||File2writename.isempty ()) {Log.warn ("The name of the file to append in the archive is null or empty."); return; } archivestreamfactory ASF=Newarchivestreamfactory (); File Tempfile=NewFile (Tarpath, "Tmptar.tar"); Tempfile.createnewfile (); Try{FileInputStream fis=NewFileInputStream (Tarfile); Archiveinputstream AIS=asf.createarchiveinputstream (Archivestreamfactory.tar, FIS); FileOutputStream Fos=NewFileOutputStream (tempfile); Archiveoutputstream AOS=Asf.createarchiveoutputstream (Archivestreamfactory.tar, FOS); //Copy the existing entriesArchiveentry NextEntry; while((NextEntry = Ais.getnextentry ())! =NULL) {aos.putarchiveentry (nextentry); Ioutils.copy (AIS, AOS); Aos.closearchiveentry (); } //Create the new entryTararchiveentry entry =Newtararchiveentry (file2writename); Entry.setsize (Filetoadd.length ()); Aos.putarchiveentry (entry); Ioutils.copy (NewFileInputStream (Filetoadd), AOS); Aos.closearchiveentry (); Aos.finish (); Ais.close (); Aos.close (); //copies the new file over the oldTarfile.delete (); Tempfile.renameto (Tarfile); } Catch(archiveexception e) {log.error (E.getmessage (), E); } Catch(IOException e) {log.error (E.getmessage (), E); } finally{fileutils.deletequietly (filetoadd); }}
Http://stackoverflow.com/questions/12890508/how-to-append-files-to-a-tar-archive-using-apache-commons-compress?rq=1
How to append files to a. Tar archive using Apache Commons Compress? (EXT)