I have an existing zipfile "main.zip". I want to replace a single file in it, "say main.zip/foo."
http://docs.oracle.com/javase/7/docs/api/java/util/zip/ZipOutputStream.html
However, this does not do what I want, as it creates a new Zip file -- and thus I'd have to add in all the existing entries in main.zip also.
Is there a way to "replace" a single file within a Zip archive in Java? (Without re-creating a new zip archive and copying over all the old data).
I think you are in luck.
Using the java 7 java.nio.file.FileSystem
together with Files.copy()
I managed to insert a textfile into a large zipfile in a split second.
public static void main(String[] argv) {
Path myFilePath = Paths.get("c:/dump2/mytextfile.txt");
Path zipFilePath = Paths.get("c:/dump2/myarchive.zip");
try( FileSystem fs = FileSystems.newFileSystem(zipFilePath, null) ){
Path fileInsideZipPath = fs.getPath("/mytextfile.txt");
Files.copy(myFilePath, fileInsideZipPath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It 'mounts' the zip using the ZipFileSystem Provider. Then you can just copy whatever you want into it. The changes seem to take place on fs.close()