begin process at 2010 02 10 11:03:01
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Divers

 > ZIPPER / DÉZIPPER UN FICHIER, UN DOSSIER

ZIPPER / DÉZIPPER UN FICHIER, UN DOSSIER


 Information sur la source

Note :
Aucune note
Catégorie :Divers Classé sous :zip, zipper, ziper, déziper, dézipper Niveau :Initié Date de création :11/06/2007 Vu / téléchargé :12 528 / 525

Auteur : tarzent

Ecrire un message privé
Commentaire sur cette source (7)
Ajouter un commentaire et/ou une note

 Description

Compresse / décompresse un fichier ou un dossier au format zip.

Source

  • import java.io.BufferedInputStream;
  • import java.io.BufferedOutputStream;
  • import java.io.File;
  • import java.io.FileInputStream;
  • import java.io.FileOutputStream;
  • import java.io.IOException;
  • import java.io.InputStream;
  • import java.io.OutputStream;
  • import java.util.zip.Deflater;
  • import java.util.zip.ZipEntry;
  • import java.util.zip.ZipInputStream;
  • import java.util.zip.ZipOutputStream;
  • public class Zip {
  • private static final String ZIP_EXTENSION = ".zip";
  • private static final int DEFAULT_LEVEL_COMPRESSION =
  • Deflater.BEST_COMPRESSION;
  • // Remplace l'extension si le fichier cible ne fini pas par '.zip'
  • private static File getZipTypeFile(final File source, final File target)
  • throws IOException {
  • if (target.getName().toLowerCase().endsWith(ZIP_EXTENSION))
  • return target;
  • final String tName = target.isDirectory()
  • ? source.getName()
  • : target.getName();
  • final int index = tName.lastIndexOf('.');
  • return new File(
  • new StringBuilder(target.isDirectory()
  • ? target.getCanonicalPath()
  • : target.getParentFile().getCanonicalPath())
  • .append(File.separatorChar)
  • .append(index < 0 ? tName : tName.substring(0 ,index))
  • .append(ZIP_EXTENSION)
  • .toString()
  • );
  • }
  • // Compresse un fichier
  • private final static void compressFile(final ZipOutputStream out,
  • final String parentFolder, final File file)
  • throws IOException {
  • final String zipName = new StringBuilder(parentFolder)
  • .append(file.getName())
  • .append(file.isDirectory() ? '/' : "")
  • .toString();
  • // Définition des attributs du fichier
  • final ZipEntry entry = new ZipEntry(zipName);
  • entry.setSize(file.length());
  • entry.setTime(file.lastModified());
  • out.putNextEntry(entry);
  • // Traitement récursif s'il s'agit d'un répertoire
  • if (file.isDirectory()) {
  • for (final File f : file.listFiles())
  • compressFile(out, zipName.toString(), f);
  • return;
  • }
  • // Ecriture du fichier dans le zip
  • final InputStream in = new BufferedInputStream(
  • new FileInputStream(file));
  • try {
  • final byte[] buf = new byte[8192];
  • int bytesRead;
  • while (-1 != (bytesRead = in.read(buf)))
  • out.write(buf, 0, bytesRead);
  • } finally {
  • in.close();
  • }
  • }
  • // Compresse un fichier à l'adresse pointée par le fichier cible.
  • // Remplace le fichier cible s'il existe déjà.
  • public static void compress(final File file, final File target,
  • final int compressionLevel)
  • throws IOException {
  • final File source = file.getCanonicalFile();
  • // Création du fichier zip
  • final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
  • getZipTypeFile(source, target.getCanonicalFile())));
  • out.setMethod(ZipOutputStream.DEFLATED);
  • out.setLevel(compressionLevel);
  • // Ajout du(es) fichier(s) au zip
  • compressFile(out, "", source);
  • out.close();
  • }
  • public static void compress(final File file, final int compressionLevel)
  • throws IOException {
  • compress(file, file, compressionLevel);
  • }
  • public static void compress(final File file, final File target)
  • throws IOException {
  • compress(file, target, DEFAULT_LEVEL_COMPRESSION);
  • }
  • public static void compress(final File file) throws IOException {
  • compress(file, file, DEFAULT_LEVEL_COMPRESSION);
  • }
  • public static void compress(final String fileName, final String targetName,
  • final int compressionLevel) throws IOException {
  • compress(new File(fileName), new File(targetName), compressionLevel);
  • }
  • public static void compress(final String fileName,
  • final int compressionLevel) throws IOException {
  • compress(new File(fileName), new File(fileName), compressionLevel);
  • }
  • public static void compress(final String fileName, final String targetName)
  • throws IOException {
  • compress(new File(fileName), new File(targetName),
  • DEFAULT_LEVEL_COMPRESSION);
  • }
  • public static void compress(final String fileName) throws IOException {
  • compress(new File(fileName), new File(fileName),
  • DEFAULT_LEVEL_COMPRESSION);
  • }
  • // Décompresse un fichier zip à l'adresse indiquée par le dossier
  • public static void decompress(final File file, final File folder,
  • final boolean deleteZipAfter)
  • throws IOException {
  • final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(
  • new FileInputStream(file.getCanonicalFile())));
  • ZipEntry ze;
  • try {
  • // Parcourt tous les fichiers
  • while (null != (ze = zis.getNextEntry())) {
  • final File f = new File(folder.getCanonicalPath(), ze.getName());
  • if (f.exists())
  • f.delete();
  • // Création des dossiers
  • if (ze.isDirectory()) {
  • f.mkdirs();
  • continue;
  • }
  • f.getParentFile().mkdirs();
  • final OutputStream fos = new BufferedOutputStream(
  • new FileOutputStream(f));
  • // Ecriture des fichiers
  • try {
  • try {
  • final byte[] buf = new byte[8192];
  • int bytesRead;
  • while (-1 != (bytesRead = zis.read(buf)))
  • fos.write(buf, 0, bytesRead);
  • } finally {
  • fos.close();
  • }
  • } catch (final IOException ioe) {
  • f.delete();
  • throw ioe;
  • }
  • }
  • } finally {
  • zis.close();
  • }
  • if (deleteZipAfter)
  • file.delete();
  • }
  • public static void decompress(final String fileName, final String folderName,
  • final boolean deleteZipAfter)
  • throws IOException {
  • decompress(new File(fileName), new File(folderName), deleteZipAfter);
  • }
  • public static void decompress(final String fileName, final String folderName)
  • throws IOException {
  • decompress(new File(fileName), new File(folderName), false);
  • }
  • public static void decompress(final File file, final boolean deleteZipAfter)
  • throws IOException {
  • decompress(file, file.getCanonicalFile().getParentFile(), deleteZipAfter);
  • }
  • public static void decompress(final String fileName,
  • final boolean deleteZipAfter)
  • throws IOException {
  • decompress(new File(fileName), deleteZipAfter);
  • }
  • public static void decompress(final File file)
  • throws IOException {
  • decompress(file, file.getCanonicalFile().getParentFile(), false);
  • }
  • public static void decompress(final String fileName)
  • throws IOException {
  • decompress(new File(fileName));
  • }
  • public static void main(String[] args)
  • throws IOException {
  • Zip.compress("C:\\test.txt", "C:\\", Deflater.BEST_SPEED);
  • Zip.decompress("C:\\test.zip", ".", false);
  • }
  • }
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class Zip {

	private static final String ZIP_EXTENSION = ".zip";

	private static final int DEFAULT_LEVEL_COMPRESSION =
		Deflater.BEST_COMPRESSION;

	// Remplace l'extension si le fichier cible ne fini pas par '.zip'
	private static File getZipTypeFile(final File source, final File target)
	throws IOException {
		if (target.getName().toLowerCase().endsWith(ZIP_EXTENSION))
			return target;
		final String tName = target.isDirectory()
			? source.getName()
			: target.getName();
		final int index = tName.lastIndexOf('.');
		return new File(
			new StringBuilder(target.isDirectory()
					? target.getCanonicalPath()
					: target.getParentFile().getCanonicalPath())
				.append(File.separatorChar)
				.append(index < 0 ? tName : tName.substring(0 ,index))
				.append(ZIP_EXTENSION)
			.toString()
		);
	}
	
	// Compresse un fichier
	private final static void compressFile(final ZipOutputStream out,
    	final String parentFolder, final File file)
    throws IOException {
        final String zipName = new StringBuilder(parentFolder)
        	.append(file.getName())
        	.append(file.isDirectory() ? '/' : "")
        	.toString();
        
        // Définition des attributs du fichier
        final ZipEntry entry = new ZipEntry(zipName);
        entry.setSize(file.length());
    	entry.setTime(file.lastModified());
        out.putNextEntry(entry);
        
        // Traitement récursif s'il s'agit d'un répertoire
        if (file.isDirectory()) {
        	for (final File f : file.listFiles())
        		compressFile(out, zipName.toString(), f);
        	return;
        }
        
        // Ecriture du fichier dans le zip
    	final InputStream in = new BufferedInputStream(
    			new FileInputStream(file));
        try {
            final byte[] buf = new byte[8192];
            int bytesRead;
            while (-1 != (bytesRead = in.read(buf)))
                out.write(buf, 0, bytesRead);
        } finally {
            in.close();
        }
    }
	
	// Compresse un fichier à l'adresse pointée par le fichier cible.
	// Remplace le fichier cible s'il existe déjà.
	public static void compress(final File file, final File target,
		final int compressionLevel)
	throws IOException {
		final File source = file.getCanonicalFile();
		
		// Création du fichier zip
        final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
        		getZipTypeFile(source, target.getCanonicalFile())));
        out.setMethod(ZipOutputStream.DEFLATED);
        out.setLevel(compressionLevel);
        
        // Ajout du(es) fichier(s) au zip
        compressFile(out, "", source);   
        out.close();
	}
	
	public static void compress(final File file, final int compressionLevel)
	        throws IOException {
		compress(file, file, compressionLevel);
	}
	public static void compress(final File file, final File target)
	        throws IOException {
		compress(file, target, DEFAULT_LEVEL_COMPRESSION);
	}
	public static void compress(final File file) throws IOException {
		compress(file, file, DEFAULT_LEVEL_COMPRESSION);
	}
	public static void compress(final String fileName, final String targetName,
	        final int compressionLevel) throws IOException {
		compress(new File(fileName), new File(targetName), compressionLevel);
	}
	public static void compress(final String fileName,
	        final int compressionLevel) throws IOException {
		compress(new File(fileName), new File(fileName), compressionLevel);
	}
	public static void compress(final String fileName, final String targetName)
	        throws IOException {
		compress(new File(fileName), new File(targetName),
		        DEFAULT_LEVEL_COMPRESSION);
	}
	public static void compress(final String fileName) throws IOException {
		compress(new File(fileName), new File(fileName),
		        DEFAULT_LEVEL_COMPRESSION);
	}
	
	// Décompresse un fichier zip à l'adresse indiquée par le dossier
	public static void decompress(final File file, final File folder,
		final boolean deleteZipAfter)
    throws IOException {
        final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(
        		new FileInputStream(file.getCanonicalFile())));
        ZipEntry ze;
        try {    
	        // Parcourt tous les fichiers
	        while (null != (ze = zis.getNextEntry())) {
	            final File f = new File(folder.getCanonicalPath(), ze.getName());
	            if (f.exists())
	            	f.delete();
	            
	            // Création des dossiers
	            if (ze.isDirectory()) {
	                f.mkdirs();
	                continue;
	            }
	            f.getParentFile().mkdirs();
	            final OutputStream fos = new BufferedOutputStream(
	            		new FileOutputStream(f));
	            
	            // Ecriture des fichiers
	            try {
	                try {
	                    final byte[] buf = new byte[8192];
	                    int bytesRead;
	                    while (-1 != (bytesRead = zis.read(buf)))
	                        fos.write(buf, 0, bytesRead);
	                } finally {
	                    fos.close();
	                }
	            } catch (final IOException ioe) {
	                f.delete();
	                throw ioe;
	            }
	        }
        } finally {
        	zis.close();
        }
        if (deleteZipAfter)
        	file.delete();
    }
	
	public static void decompress(final String fileName, final String folderName,
		final boolean deleteZipAfter)
    throws IOException {
		decompress(new File(fileName), new File(folderName), deleteZipAfter);
	}
	public static void decompress(final String fileName, final String folderName)
    throws IOException {
		decompress(new File(fileName), new File(folderName), false);
	}
	public static void decompress(final File file, final boolean deleteZipAfter)
    throws IOException {
		decompress(file, file.getCanonicalFile().getParentFile(), deleteZipAfter);
	}
	public static void decompress(final String fileName,
		final boolean deleteZipAfter)
    throws IOException {
		decompress(new File(fileName), deleteZipAfter);
	}
	public static void decompress(final File file)
    throws IOException {
		decompress(file, file.getCanonicalFile().getParentFile(), false);
	}
	public static void decompress(final String fileName)
    throws IOException {
		decompress(new File(fileName));
	}

	
	public static void main(String[] args)
	throws IOException {
		Zip.compress("C:\\test.txt", "C:\\", Deflater.BEST_SPEED);
		Zip.decompress("C:\\test.zip", ".", false);
    }
}


 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 Sources du même auteur

JCALENDAR INTERNATIONALISÉ
Source avec Zip ENVOI ET LECTURE DE MAILS (+AUTHENTIFICATION +SSL +PIÈCES JO...
RTF TO HTML

 Sources de la même categorie

Source avec Zip Source avec une capture TRADUCTEUR FRANÇAIS --> NERLANDAIS par edouard333
Source avec Zip IA POUR DISCUTER par edouard333
Source avec Zip Source avec une capture JSUBTITLE1.0 par darrylsite
Source avec Zip COMPILATEUR PASCAL par youma85
Source avec Zip CONTENEUR DE COMPOSANT HETEROGENES par mad_charif

 Sources en rapport avec celle ci

Source avec Zip ZIP_FIC -- ARCHIVAGE AU FORMAT ZIP D'UN RÉPERTOIRE par StevosTeen
Source avec Zip JOURNAL INTIME par sheorogath
Source avec Zip ZIPEUR DE FICHIER 2 par grand_jeanluc
ZIPEUR DE FICHIER par harryharry
ZIP, POUR ZIPER ET DÉZIPER UN FICHIER AISÉMENT EN JAVA par JHelp

Commentaires et avis

Commentaire de sheorogath le 12/06/2007 18:20:57 administrateur CS

heu pouruqoi tu met des final a tout bout de champ ? static ?

Commentaire de petifa le 07/07/2007 22:42:10

oui c'est un peu bizard tout ces final ...
Jai pas compris non plus pourquoi tu as mis plusieurs fois des fonctions compress et decompress avec des types de param differents ...
petifa

Commentaire de Karibou38 le 18/03/2008 17:05:40

J'avais juste besoin d'une fonction pour dézipper un fichier et ton code marche parfaitement :)
Merci

Commentaire de tarzent le 19/03/2008 11:13:26

Salut tout le monde,

'final' c'est de l'optimisation. Je vois qu'il y a toujours autant de monde qui les connaît...

Il y a effectivement plusieurs constructeurs pour compress et decompress : en fonction de ce que vous avez sous la main (un objet File, une String...) vous utilisez plutôt l'un ou l'autre.

++

Commentaire de sheorogath le 21/03/2008 17:18:46 administrateur CS

tout mettre en final n'est peut etre pas la peine d'en mettre autant

Commentaire de Krazymins le 23/03/2009 11:52:00

Bonjour tout le monde,

comment faire pour placer les dossier dans le zip et ne pas tout avoir à la racine du zip svp ?  (garder l'arborescence du dossier que l'on veut zipper)

Thanks

Commentaire de kmeleon1 le 24/06/2009 15:42:21

Bonjour,

Félicitations pour ta source, elle m'a été très utile.
elle mérite au moins un 8/10

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

(archive="applet.zip")et(codebase="downloads") [ par furiedonkey ] Bonjour je monte un site sur le java et j'ai un petit problème,dans mon dossier racine de mon site exemple (mon site) et dans le dossier(mon site) j'a problème d'accent sur les zip [ par doria123 ] Salut,J'ai un petit problème lorsque je zippe des fichiers qui contiennent caractères spéciaux comme les "é" ou les "è".par exemple, pour un fichier q download d'un fichier zip sur un site internet [ par yann.jaunin ] Hello,j'essaye de télécharger un fichier zip qui se trouve sur un site internet. Je suis débutant donc soyez indulgent :-)voici l'erreur que j'aie :un How to "Splitter un fichier zip généré en java ? " [ par homerosaur ] Salut à tous,je recherche un moyen de splitter un fichier zip que je génère en java.Mille merci d'avance à qui pourrait m'aidertiti jdbc OracleDriver classes111.zip [ par schneider ] J'aurais besoin du fichier classes111.zip pour pouvoir accéder à une base Oracle 7.3.4. Ce fichier étant introuvable sur le net (trop vieux surement), Compression en zip et zw [ par OxN ] Je dois monter une appli en Java me permettant de compresser (et decompresser) des fichiers en zip ou zw.. le problème, c'est que je suis débutant en Zip, servlet, et fichier Excel [ par as634 ] J'ai créé un fichier excel grace à jExcel. Je voudrais insérer ce fichier dans une archive zip qui sera renvoyée par ma servlet.Voici mon code pour la mysql et zip [ par isdine ] Bonjour Comment pourrait on mettre dans une base de donnee un fichier zipper.Merci d'avance PROBLEME DE ZIP [ par gui_llaume1 ] Bonjour &#224; tous,J'explique mon cas.Je cr&#233;e dans une appli swing &#224; un moment un fichier zip &#224; partir d'un tableau de String contenan ajouter ou supprimer des fichiers dans un ZIP existant [ par larecrue ] Voila mon probleme,Je zippe dans des nouvelles archives et dezzippe sans probleme. Par contre, je n'arrive pas a modifier des archives zip existantes


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,936 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales