1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
public void addFilesToExistingZip(File zipFile,
String file, boolean fullPath) throws IOException {
// get a temp file
File tempFile = File.createTempFile(zipFile.getName(), null);
// delete it, otherwise you cannot rename your existing zip to it.
tempFile.delete();
ArrayList name = new ArrayList();
boolean renameOk=zipFile.renameTo(tempFile);
if (!renameOk)
{
throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
}
byte[] buf = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry = zin.getNextEntry();
while (entry != null) {
name.add(entry.getName());
entry = zin.getNextEntry();
}
zin.close();
ZipInputStream zin2 = new ZipInputStream(new FileInputStream(tempFile));
if (fullPath) {
name.remove(file);
InputStream in = new FileInputStream(file);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(file));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Add ZIP entry to output stream.
entry = zin2.getNextEntry();
while (entry != null) {
if (name.contains(entry.getName())) {
out.putNextEntry(new ZipEntry(entry.getName()));
// Transfer bytes from the ZIP file to the output file
int lent;
while ((lent = zin2.read(buf)) > 0) {
out.write(buf, 0, lent);
}
}
entry = zin2.getNextEntry();
}
// Close the streams
zin2.close();
// Complete the entry
out.closeEntry();
in.close();
} else {
name.remove(new File(file).getName());
InputStream in = new FileInputStream(file);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(new File(file).getName()));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Add ZIP entry to output stream.
entry=zin2.getNextEntry();
while (entry != null) {
if (name.contains(entry.getName())) {
out.putNextEntry(new ZipEntry(entry.getName()));
// Transfer bytes from the ZIP file to the output file
int lent;
while ((lent = zin2.read(buf)) > 0) {
out.write(buf, 0, lent);
}
}
entry = zin2.getNextEntry();
}
// Close the streams
zin2.close();
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
tempFile.delete();
} |
Partager