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 94 95 96 97 98 99
| public void zipContent()
{
ZipOutputStream zipout;
try
{
zipout = new ZipOutputStream("destination zip file");
zipDir("main source directory", zipout, "");
zipout.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private void zipDir(String source, ZipOutputStream zipout, String relativeDir) throws IOException
{
File zipDir = new File(source);
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
// Loop through dirList, and zip the files.
for (int i = 0; i < dirList.length; i++)
{
File f = new File(zipDir, dirList[i]);
if (f.isDirectory())
{
// If the File object is a directory, call this
// function again to add its content recursively.
String filePath = f.getPath();
String name = f.getName();
if (!name.endsWith("/")) name += "/";
zipEntries.put(name, name);
if (relativeDir.equals(""))
{
ZipEntry anEntry;
anEntry = new ZipEntry(name);
zipout.putNextEntry(anEntry);
zipout.closeEntry();
zipDir(filePath, zipout, name);
}
else
{
ZipEntry anEntry;
if (!relativeDir.endsWith("/"))
relativeDir += "/";
anEntry = new ZipEntry(relativeDir + name);
zipout.putNextEntry(anEntry);
zipDir(filePath, zipout, relativeDir + name);
}
// Loop again.s
continue;
}
// Create a FileInputStream on top of f.
FileInputStream fis = new FileInputStream(f);
ZipEntry anEntry;
if ((!relativeDir.endsWith("/")) && (!relativeDir.equals("")))
relativeDir += "/";
if (!relativeDir.equals(""))
{
anEntry = new ZipEntry(relativeDir + f.getName());
}
else
{
anEntry = new ZipEntry(f.getName());
}
// Place the zip entry in the ZipOutputStream object.
zipout.putNextEntry(anEntry);
zipEntries.put(anEntry.getName(), anEntry.getName());
// Now write the content of the file to the ZipOutputStream.
while ((bytesIn = fis.read(readBuffer)) != -1)
{
zipout.write(readBuffer, 0, bytesIn);
}
// Close the Stream.
zipout.closeEntry();
fis.close();
}
} |
Partager