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
|
/**
* Fonction pour zipper un répertoire ou un fichier.
* Cela ne prend pas en compte les répertoires supérieurs à celui que l'on veut zipper (ils n'apparaissent pas dans le zip)
* @param repAZip répertoire que l'on veut zipper
* @return vrai si la compression s'est bien déroulée, faux sinon
* @see addDirToZip
*/
public static boolean zipper(File repAZip) {
// nom du fichier zip
String nameZipFile = new String("pouet");
// on déclare le nom du fichier zip -> il correspond au nom du répertoire que l'on veut zipper'
File zipFile = new File(rep_colis, nameZipFile+".zip");
try {
// on assigne de flux zip au fichier Zip
ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
// méthode
zipStream.setMethod(ZipOutputStream.DEFLATED);
// niveau de compression
zipStream.setLevel(Deflater.BEST_COMPRESSION);
// on lance la compression de ce répertoire
if(repAZip.isDirectory()) {
addDirToZip("",repAZip, zipStream);
}else {
// si c'est fichier, on le zip
try {
FileInputStream in = new FileInputStream(repAZip);
byte[] bytes = new byte[in.available()];
in.read(bytes); in.close();
ZipEntry entry = new ZipEntry(repAZip.getName());
entry.setTime(repAZip.lastModified());
zipStream.putNextEntry(entry);
zipStream.write(bytes);
zipStream.closeEntry();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Problème lors de la compression du répertoire");
return false;
}
}
// une fois terminé, on ferme le flux
zipStream.close();
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
private static boolean addDirToZip(String anArchPath, File aDir, ZipOutputStream zipStream) {
File list[] = aDir.listFiles();
for (int ind = 0; ind < list.length; ind++) {
if (list[ind].isDirectory()) {
addDirToZip(anArchPath + list[ind].getName() + "/", list[ind], zipStream);
}else {
try {
FileInputStream in = new FileInputStream(list[ind]);
byte[] bytes = new byte[in.available()];
in.read(bytes); in.close();
ZipEntry entry = new ZipEntry(anArchPath + list[ind].getName());
entry.setTime(list[ind].lastModified());
zipStream.putNextEntry(entry);
zipStream.write(bytes);
zipStream.closeEntry();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Problème lors de la compression du répertoire");
return false;
}
}
}
return true;
} |