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
UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|