IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Entrée/Sortie Java Discussion :

Compresser dossier et sous dossier (Zip) ?


Sujet :

Entrée/Sortie Java

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Mars 2010
    Messages
    23
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2010
    Messages : 23
    Points : 14
    Points
    14
    Par défaut Compresser dossier et sous dossier (Zip) ?
    Bonjour à tous !

    Je requière votre aide pour un problème de compression de dossier en Java.

    Je vous explique mon problème :

    Avec mon logiciel, je crée à la fin un répertoire, appelons le "folder" (qui par la suite sera upload sur un ftp) contenant des sous dossiers qui eux mêmes contiennent des fichiers, mais le problème, c'est que je n'arrive pas à compresser "Folder" avec les sous dossiers qu'il contient.

    C'est pourquoi je vous demande un lien, une méthode, un code source, m'aidant à réaliser ceci, c'est à dire compresser un dossier avec ses sous-dossiers et ses fichiers en un seul ZIP.

    Cordialement,
    SoGeek.
    PS : Bonne journée à vous, et merci à l'âme charitable qui m'aidera

  2. #2
    Membre régulier
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    160
    Détails du profil
    Informations personnelles :
    Âge : 38
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Octobre 2006
    Messages : 160
    Points : 111
    Points
    111
    Par défaut
    Regarde de ce côté là, tu devrais trouver ce qu'il te faut.

    http://java.developpez.com/sources/?...CompressionZip

  3. #3
    Membre à l'essai
    Profil pro
    Inscrit en
    Mars 2010
    Messages
    23
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2010
    Messages : 23
    Points : 14
    Points
    14
    Par défaut
    Bonsoir,

    Tout d'abord merci pour ta réponse,
    J'avais déjà essayé ce code, mais le problème est que dans

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    	public static String unAccent(String s) {
    		String temp = Normalizer.normalize(s, Normalizer.DECOMP, 0);
    		return temp.replaceAll("[^\\p{ASCII}]","");
    	}
    Normalizer.DECOMP est souligné en rouge chez moi, j'ai bien importé sun.text, j'ai bien placé le code où il fallait, et Normalizer.DECOMP se souligne toujours en rouge sans aucunes possibilité de réparer ça.

    Avez-vous une solution ?

    Cordialement,
    SoGeek,
    Bonne soirée à vous !

  4. #4
    Membre régulier
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    160
    Détails du profil
    Informations personnelles :
    Âge : 38
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Octobre 2006
    Messages : 160
    Points : 111
    Points
    111
    Par défaut
    Au temps pour moi, en plus j'ai eu le coup aussi quand j'ai voulu le récupérer.

    Voici donc une autre classe utilitaire (java 6 requis il me semble) trouvé sur le net :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
     
    package global;
     
    import java.io.*;
    import java.util.zip.*;
     
    /**
     * Classe d'utilitaires pour les compressions et décompression Zip, GZip, JAR...
     * @author iubito (Sylvain Machefert)
     */
    public class OutilsZip {
     
    	/** Taille du buffer pour les lectures/écritures */
    	private static final int BUFFER_SIZE = 8 * 1024;
     
    	/**
             * Décompresse un GZIP contenant un fichier unique.
             * 
             * Efface le filedest avant de commencer.
             * @param gzsource Fichier GZIP é décompresser
             * @param filedest Nom du fichier destination oé sera sauvegardé le fichier
             * contenu dans le GZIP.
             * @throws FileNotFoundException si le fichier GZip n'existe pas
             * @throws IOException 
             * @see http://javaalmanac.com/egs/java.util.zip/UncompressFile.html?l=rel
             */
    	public static void gunzip(String gzsource, String filedest)
    		throws FileNotFoundException, IOException {
    		// Open the compressed file
    		GZIPInputStream in = new GZIPInputStream(new FileInputStream(gzsource));
    		try {
    			BufferedInputStream bis = new BufferedInputStream(in);
    			try {
    				// Open the output file
    				OutputStream out = new FileOutputStream(filedest);
    				try {
    					BufferedOutputStream bos = new BufferedOutputStream(out);
    					try {
    						// Transfer bytes from the compressed file to the output file
    						byte[] buf = new byte[BUFFER_SIZE];
    						int len;
    						while ((len = bis.read(buf, 0, BUFFER_SIZE)) != -1) {
    							bos.write(buf, 0, len);
    						}
    						buf = null;
    					}
    					finally {
    						bos.close();
    					}
    				}
    				finally {
    					out.close();
    				}
    			}
    			finally {
    				bis.close();
    			}
    		}
    		finally {
    			in.close();
    		}
    	}
     
    	/**
             * Compresse un fichier dans un GZIP.
             * 
             * Efface le filedest avant de commencer.
             * @param filesource Fichier é compresser
             * @param gzdest Fichier GZIP cible
             * @throws FileNotFoundException si le fichier source n'existe pas ou si le GZIP
             * n'existe pas aprés la compression
             * @throws IOException 
             * @see http://javaalmanac.com/egs/java.util.zip/CompressFile.html?l=rel
             * @see http://java.developpez.com/livres/penserenjava/?chap=12&page=3
             */
    	public static void gzip(String filesource, String gzdest)
    		throws FileNotFoundException, IOException {
    		// Create the GZIP output stream
    		GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(gzdest));
    		try {
    			BufferedOutputStream bos = new BufferedOutputStream(out);
    			try {
    				// Open the input file
    				FileInputStream in = new FileInputStream(filesource);
    				try {
    					BufferedInputStream bis = new BufferedInputStream(in);
    					try {
    						// Transfer bytes from the input file to the GZIP output stream
    						byte[] buf = new byte[BUFFER_SIZE];
    						int len;
    						while ((len = bis.read(buf, 0, BUFFER_SIZE)) > 0) {
    							bos.write(buf, 0, len);
    						}
    						buf = null;
    					}
    					finally {
    						bis.close();
    					}
    				}
    				finally {
    					in.close();
    				}
    			}
    			finally {
    				bos.close();
    			}
    		}
    		finally {
    			out.close();
    		}
    		if (!new File(gzdest).exists())
    			throw new FileNotFoundException("Le fichier " + gzdest + " n'a pas été créé");
    	}
     
    	/**
             * Décompresse l'archive Zip dans un répertoire.
             * Réutilise les noms des répertoires lors de la décompression.
             * @param zipsrc
             * @param basedirdest
             * @throws FileNotFoundException
             * @throws IOException
             * @throws SecurityException
             */
    	public static void unzipToDir(String zipsrc, String basedirdest)
    		throws FileNotFoundException, IOException, SecurityException {
     
    		unzipToDir(new FileInputStream(zipsrc), basedirdest);
    	}
     
    	/**
             * Décompresse le flux <tt>InputStream</tt> Zip dans un répertoire.
             * Réutilise les noms des répertoires lors de la décompression.
             * @param zipsrc
             * @param basedirdest
             * @throws SecurityException
             * @throws IOException
             */
    	public static void unzipToDir(InputStream inzip, String basedirdest)
    		throws IOException, SecurityException {
     
    		File base = new File(basedirdest);
    		if (!base.exists())
    			base.mkdirs();
     
    		try {
    			CheckedInputStream checksum = new CheckedInputStream(inzip, new Adler32());
    			try {
    				//Buffer sur le zip
    				BufferedInputStream bis = new BufferedInputStream(checksum);
    				try {
    					ZipInputStream zis = new ZipInputStream(bis);
    					try {
    						ZipEntry entry;
    						File f;
    						int count;
    						byte[] buf = new byte[BUFFER_SIZE];
    						BufferedOutputStream bos;
    						FileOutputStream fos;
    						//Parcours les entrées du zip
    						while ((entry = zis.getNextEntry()) != null) {
    							f = new File(basedirdest, entry.getName());
    							if (entry.isDirectory())
    								f.mkdirs();
    							else { //L'entry semble étre un fichier
    								//Si contient un / on crée les répertoires, car parfois on a pas dir/ avant dir/fichier.ext
    								int l = entry.getName().lastIndexOf('/');
    								if (l != -1) {
    									new File(basedirdest, entry.getName().substring(0, l)).mkdirs();
    								}
    								fos = new FileOutputStream(f);
    								try {
    									bos = new BufferedOutputStream(fos, BUFFER_SIZE);
    									try {
    										//Ecriture du fichier
    										while ((count = zis.read(buf, 0, BUFFER_SIZE)) != -1) {
    											bos.write(buf, 0, count);
    										}
    									}
    									finally {
    										bos.close();
    									}
    								}
    								finally {
    									fos.close();
    								}
    							}
    							if (entry.getTime() != -1) {
    								f.setLastModified(entry.getTime());
    							}
    						}
    					}
    					finally {
    						zis.close();
    					}
    				}
    				finally {
    					bis.close();
    				}
    			}
    			finally {
    				checksum.close();
    			}
    		} finally {
    			inzip.close();
    		}
    	}
     
    	/**
             * Zippe récursivement un répertoire, en mettant les chemins de fichiers en relatif.
             * <p>Les accents des noms de fichiers sont supprimés, voir
             * {@link OutilsString#sansAccents(String)} pour plus de détails.
             * @param dirsource Le répertoire é compresser
             * @param zipdest Le nom du fichier zip résultat
             * @throws FileNotFoundException
             * @throws IOException
             */
    	public static void zipDir(String dirsource, String zipdest)
    		throws FileNotFoundException, IOException {
     
    		//Création d'un flux d'écriture vers un fichier
    		FileOutputStream fos = new FileOutputStream(zipdest);
    		try {
    			//Ajout du checksum : Adler32 (plus rapide) ou CRC32
    			CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32());
    			try {
    				//Création d'un buffer de sortie afin d'améliorer les performances
    				BufferedOutputStream bos = new BufferedOutputStream(checksum, BUFFER_SIZE);
    				try {
    					//Création d'un flux d'écriture Zip vers le fichier é travers le buffer
    					ZipOutputStream zos = new ZipOutputStream(bos);
    					try {
    						//Compression maximale
    						try {
    							zos.setMethod(ZipOutputStream.DEFLATED);
    							zos.setLevel(Deflater.BEST_COMPRESSION);
    						}
    						catch (Exception ignor) {}
    						zipDir(dirsource, null, zos);
    					}
    					finally {
    						zos.close();
    					}
    				}
    				finally {
    					bos.close();
    				}
    			}
    			finally {
    				checksum.close();
    			}
    		}
    		finally {
    			fos.close();
    		}
    	}
     
    	/**
             * étant donné un répertoire base (qui n'est pas inclu dans les entrées
             * <tt>ZipEntry</tt>), le répertoire courant é zipper, et le <tt>ZipOutputStream</tt>
             * de sortie, ajoute les fichiers dans le zip, ou s'appelle récursivement pour ajouter
             * un répertoire fils.
             * @param basedir
             * @param currentdir
             * @param zos
             * @throws FileNotFoundException
             * @throws IOException
             * @see http://www.developpez.net/forums/viewtopic.php?p=1724764
             */
    	private static void zipDir(String basedir, String currentdir, ZipOutputStream zos)
    		throws FileNotFoundException, IOException {
    		//create a new File object based on the directory we have to zip
    		File zipDir = (currentdir != null) ? new File(basedir, currentdir) : new File(basedir);
    		//get a listing of the directory content
    		String[] dirList = zipDir.list();
    		byte[] readBuffer = new byte[BUFFER_SIZE];
    		int bytesIn = 0;
    		//On met pas File.separator, mais "/" parce que c'est le caractére utilisé
    		//dans les ZIP.
    		String currentdir2 = (currentdir != null) ? (currentdir + "/") : "";
     
    		File f;
    		FileInputStream fis;
    		BufferedInputStream bis;
    		ZipEntry anEntry;
    		//Create an empty entry with just dir name, like WinZip, so unzipToDir will
    		//behave correctly.
    		if (currentdir2.length() > 0) {
    			anEntry = new ZipEntry(StringHelper.sansAccents(currentdir2));
    			zos.putNextEntry(anEntry);
    			zos.closeEntry();
    		}
    		//loop through dirList, and zip the files
    		for (int i = 0; i < dirList.length; i++) {
    			f = new File(zipDir, dirList[i]);
    			if (!f.exists())
    				continue;
    			if (f.isDirectory()) {
    				//if the File object is a directory, call this
    				//function again to add its content recursively
    				zipDir(basedir, currentdir2 + dirList[i], zos);
    				continue;
    			}
    			//if we reached here, the File object f was not a directory
    			//create a FileInputStream on top of f
    			fis = new FileInputStream(f);
    			try {
    				bis = new BufferedInputStream(fis, BUFFER_SIZE);
    				try {
    					//create a new zip entry
    					anEntry = new ZipEntry(StringHelper.sansAccents(currentdir2 + dirList[i]));
    					anEntry.setTime(f.lastModified());
     
    					//place the zip entry in the ZipOutputStream object
    					zos.putNextEntry(anEntry);
    					//now write the content of the file to the ZipOutputStream
    					while ((bytesIn = bis.read(readBuffer, 0, BUFFER_SIZE)) != -1) {
    						zos.write(readBuffer, 0, bytesIn);
    					}
    					zos.closeEntry();
    				}
    				finally {
    					bis.close();
    				}
    			}
    			finally {
    				//close the Stream
    				fis.close();
    			}
    		}
    	}
     
     
     
    }

Discussions similaires

  1. Comment lister dossiers et sous dossiers
    Par sword999 dans le forum Entrée/Sortie
    Réponses: 1
    Dernier message: 11/08/2006, 11h36
  2. Lister sous-dossiers d'un dossier défini
    Par mathieumg dans le forum C
    Réponses: 10
    Dernier message: 19/07/2006, 10h20
  3. lister dossier et sous dossier
    Par wabit dans le forum C
    Réponses: 6
    Dernier message: 06/06/2006, 16h48
  4. [VB6]lister les dossiers et sous dossier
    Par Jacen dans le forum VB 6 et antérieur
    Réponses: 2
    Dernier message: 28/04/2006, 08h06
  5. Réponses: 4
    Dernier message: 25/04/2006, 16h16

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo