Accueil > > > ZIPPER / DÉZIPPER UN FICHIER, UN DOSSIER
ZIPPER / DÉZIPPER UN FICHIER, UN DOSSIER
Information sur la source
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);
}
}
Sources de la même categorie
Commentaires et avis
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 à tous,J'explique mon cas.Je crée dans une appli swing à un moment un fichier zip à 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
|
Derniers Blogs
[FRAMEWORK 4] LES TASKS ET LE THREAD UI[FRAMEWORK 4] LES TASKS ET LE THREAD UI par fathi
Je viens de passer quelques temps au TechDay's et j'ai pu voir pas mal de session intéressante. Par contre une chose m'a un peu étonné lors de certaines de ces sessions qui abordaient les améliorations du framework .NET (donc le 4.5) : en gros, bea...
Cliquez pour lire la suite de l'article par fathi WORKFLOW FOUNDATION 3 A UN PIED DANS LA TOMBEWORKFLOW FOUNDATION 3 A UN PIED DANS LA TOMBE par JeremyJeanson
Depuis déjà un an, je conseille vivement les utilisateurs de Workflow Foundation 3 à migrer vers la version 4. L'information qui va suivre ne devrait donc pas trop prendre au dépourvu les personnes qui m'ont suivi. Je profite de ce poste, pour faire le re...
Cliquez pour lire la suite de l'article par JeremyJeanson TECHDAYS PARIS 2012 : NOUVELLES TENDANCES DU POSTE DE TRAVAIL - BRING YOUR OWN PCTECHDAYS PARIS 2012 : NOUVELLES TENDANCES DU POSTE DE TRAVAIL - BRING YOUR OWN PC par ROMELARD Fabrice
Speakers: Thierry Rapatout, Antoine Petit et Xavier Trebbia Cette session entre dans le cadre des RDV Décideurs des TechDays 2012, elle est liée à la consumérisation de l'IT et la mise en place du "DeskTop as a Service" dans de plus en ...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice TECHDAYS PARIS 2012 : SYSTEM CENTER SERVICE MANAGER 2012 VUE D'ENSEMBLETECHDAYS PARIS 2012 : SYSTEM CENTER SERVICE MANAGER 2012 VUE D'ENSEMBLE par ROMELARD Fabrice
Speakers: Julien Marechal, Gautier Confiant, Sébastien MEYER La session débute par le positionnement de la solution System Center par rapport aux concepts d'organisation ITIL. Le portail du catalogue de se...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice TECHDAYS PARIS 2012 : PLEINIèRE SECOND JOURTECHDAYS PARIS 2012 : PLEINIèRE SECOND JOUR par ROMELARD Fabrice
Après une première journée dédiée aux développeurs, cette seconde journée est dédiée au monde des entreprises et de ses applications. Ainsi, cette pleinière est dédiée à faire un 360 de l'évolution des applications Business aux demandes ac...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Forum
RE : SQLRE : SQL par Julien39
Cliquez pour lire la suite par Julien39
Logiciels
Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning COLLECTOR PLUS (3.00B)COLLECTOR PLUS (3.00B)COLLECTOR PLUS version 3.00B est un logiciel utilisant une base de données alimentée par :
- L... Cliquez pour télécharger COLLECTOR PLUS PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO LettresFaciles 2011 (8.0.0.1)LETTRESFACILES 2011 (8.0.0.1)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles 2011
|