Una clase de herramienta de descompresión de compresión con cremallera simple escrita con Java Basic Class
La copia del código es la siguiente:
paquete Sun.net.helper;
import java.io.*;
import java.util.logging.logger;
import java.util.zip.*;
clase pública Ziputil {
Private Final Static Logger logger = logger.getLogger (ziputil.class.getName ());
Private static final int tamper = 1024*10;
/**
* Comprima el directorio especificado en un archivo zip con el mismo nombre que el directorio, y personalice la ruta de compresión
* @Param SourceFilePath Ruta del archivo de destino
* @param zipFilePath Especifique la ruta del archivo zip
* @devolver
*/
Public Static Boolean Zip (String SourceFilePath, String ZipFilepath) {
resultado booleano = falso;
Archivo fuente = nuevo archivo (SourceFilePath);
if (! fuente.exists ()) {
logger.info (SourceFilePath+"no existe");
resultado de retorno;
}
if (! Source.isDirectory ()) {
logger.info (SourceFilePath+"no es un directorio");
resultado de retorno;
}
Archivo zipfile = nuevo archivo (zipFilePath+"/"+source.getName ()+". Zip");
if (zipfile.exists ()) {
logger.info (zipFile.getName ()+"ya está existido");
resultado de retorno;
}demás{
if (! ZipFile.getParentFile (). Exists ()) {
if (! ZipFile.getParentFile (). MkDirs ()) {
logger.info ("no puede crear archivo"+zipfile.getName ());
resultado de retorno;
}
}
}
logger.info ("Creación de archivo zip ...");
FileOutputStream dest = null;
ZipOutputStream out = null;
intentar {
des = nuevo FileOutputStream (ZIPFile);
CheckEdOutputStream checksum = new CheckEdOutputStream (des, new ADler32 ());
out = new ZipoutputStream (new BufferedOutputStream (chechsum));
out.setMethod (zipoutputstream.deflated);
compress (fuente, out, fuente.getName ());
resultado = verdadero;
} catch (FileNotFoundException e) {
E.PrintStackTrace ();
} finalmente {
if (out! = null) {
intentar {
out.closeEntry ();
} Catch (ioException e) {
E.PrintStackTrace ();
}
intentar {
out.close ();
} Catch (ioException e) {
E.PrintStackTrace ();
}
}
}
if (resultado) {
logger.info ("hecho");
}demás{
logger.info ("Fail");
}
resultado de retorno;
}
compress void static privado (archivo de archivo, zipoutputstream out, string mainfileName) {
if (file.isfile ()) {
FileInputStream fi = null;
BufferedInputStream Origin = null;
intentar {
fi = new FileInputStream (archivo);
origen = new BufferedInputStream (FI, Buffer);
int index = file.getabsolutePath (). indexOf (mainFileName);
Cadena entryname = file.getabsolutePath (). Substring (index);
System.out.println (EntryName);
Zipentry entry = new ZipEntry (EntryName);
out.putNextEntry (entrada);
byte [] data = new Byte [buffer];
int cuenta;
while ((count = origen.read (data, 0, buffer))! = -1) {
out.write (datos, 0, recuento);
}
} catch (FileNotFoundException e) {
E.PrintStackTrace ();
} Catch (ioException e) {
E.PrintStackTrace ();
} finalmente {
if (origen! = null) {
intentar {
origin.close ();
} Catch (ioException e) {
E.PrintStackTrace ();
}
}
}
} else if (file.isDirectory ()) {
Archivo [] fs = file.listFiles ();
if (fs! = null && fs.length> 0) {
para (archivo f: fs) {
compresa (f, out, mainfileName);
}
}
}
}
/**
* Descomprima el archivo ZIP al directorio especificado.
* @param zipfile
* @param desestpath
* @devolver
*/
Public Static Boolean Unzip (File ZipFile, String DestPath) {
resultado booleano = falso;
if (! zipfile.exists ()) {
logger.info (zipfile.getName ()+"no existe");
resultado de retorno;
}
Archivo de archivo = nuevo archivo (DestPath);
if (! Target.exists ()) {
if (! Target.mkdirs ()) {
logger.info ("no puede crear archivo"+target.getName ());
resultado de retorno;
}
}
Cadena mainFileName = zipFile.getName (). Reemplazar (". Zip", "");
Archivo TargetFile = nuevo archivo (DestPath+"/"+MainFileName);
if (TargetFile.Exists ()) {
logger.info (targetFile.getName ()+"ya existir");
resultado de retorno;
}
Zipinputstream zis = null;
logger.info ("Iniciar archivo unzip ...");
intentar {
FileInputStream fis = new FileInputStream (ZIPFile);
CheckEdInputStream checksum = new CheckEdInputStream (FIS, new ADler32 ());
zis = new ZipInputStream (new BufferedInputStream (CHECKSUM));
Entrada ZipEntry;
while ((entry = zis.getNextEntry ())! = NULL) {
int cuenta;
Datos de byte [] = new Byte [buffer];
String EntryName = Entry.getName ();
int index = entryname.IndexOf (mainFileName);
String newEntryName = DestPath+"/"+EntryName.Substring (índice);
System.out.println (newEntryName);
Archivo temp = nuevo archivo (newEntryName) .getParentFile ();
if (! temp.exists ()) {
if (! temp.mkdirs ()) {
tirar nueva runtimeException ("Crear archivo" +temp.getName () +"fail");
}
}
FileOutputStream fos = new FileOutputStream (newEntryName);
BufferedOutputStream Dest = new BufferedOutputStream (FOS, Buffer);
while ((count = zis.read (data, 0, buffer))! = -1) {
dest.write (datos, 0, recuento);
}
dest.flush ();
dest.close ();
}
resultado = verdadero;
} catch (FileNotFoundException e) {
E.PrintStackTrace ();
} Catch (ioException e) {
E.PrintStackTrace ();
} finalmente {
if (zis! = null) {
intentar {
zis.close ();
} Catch (ioException e) {
E.PrintStackTrace ();
}
}
}
if (resultado) {
logger.info ("hecho");
}demás{
logger.info ("Fail");
}
resultado de retorno;
}
public static void main (string [] args) lanza ioexception {
//Ziputil.zip("D:/apache-MiCat-7.0.30 "," d:/temp ");
Archivo zipfile = nuevo archivo ("d: /temp/apache-mocat-7.0.30.zip");
Ziputil.unzip (zipfile, "d:/temp");
}
}
Otro ejemplo de compresión y descompresión, consulte las dos herramientas.
La copia del código es la siguiente:
paquete com.lanp;
import java.io.file;
import java.io.fileInputStream;
import java.io.fileOutputStream;
import java.io.ioException;
import java.util.zip.zipentry;
import java.util.zip.zipexception;
import java.util.zip.zipfile;
import java.util.zip.zipinputstream;
/**
* Descomprima el archivo comprimido zip al directorio especificado
*/
Clase final pública Ziptofile {
/**
* El tamaño de la memoria caché predetermina a 20480
*/
Private final static int file_buffer_size = 20480;
privado ziptofile () {
}
/**
* Descomprima el archivo comprimido zip del directorio especificado al directorio especificado
* @param zipFilePathzip ruta de archivo comprimido
* @param name de archivo comprimido zipfilenamezip
* @param TargetFileDirzip Archivo comprimido para extraer
* @Return Flag Boolean Return Value
*/
Public Static Boolean Unzip (String ZipFilePath, String ZipFileName, String TargetFiledir) {
bandera booleana = falso;
// 1.
Archivo file = null; // archivo comprimido (con ruta)
ZipFile ZipFile = NULL;
archivo = nuevo archivo (ZipFilePath + "/" + ZipFileName);
System.out.println (">>>>>>> Descompensar el archivo [" + ZipFilePath + "/" + ZipFileName + "] al Directorio [" + TargetFiledir + "] <<<<<<<ema);
if (false == file.exists ()) {
System.out.println (">>>>>>> archivo comprimido [" + zipfilepath + "/" + zipFileName + "] no existe <<<<<<<<<ema);
devolver falso;
} else if (0 == file.length ()) {
System.out.println (">>>>>>> archivo comprimido [" + zipfilepath + "/" + zipFileName + "] El tamaño es 0 y no requiere descompresión <<<<<<<");
devolver falso;
} demás {
// 2.
byte [] buf = new Byte [file_buffer_size];
int readSize = -1;
Zipinputstream zis = null;
FileOutputStream fos = null;
intentar {
// Verifique si es un archivo zip
ZipFile = new ZipFile (archivo);
zipfile.close ();
// Determinar si el directorio de destino existe.
Archivo newdir = nuevo archivo (TargetFiledir);
if (false == newdir.exists ()) {
newdir.mkdirs ();
newdir = nulo;
}
zis = new ZipInputStream (nuevo FileInputStream (File));
ZipEntry Zipentry = zis.getNextEntry ();
// Iniciar procesamiento de archivos en el paquete comprimido
while (null! = zipentry) {
Cadena zipEntryName = zipentry.getName (). Reemplazar ('//', '/');
// juzga si Zipentry es un directorio.
if (zipentry.isDirectory ()) {
int indexNumber = zipEntryName.lastIndexOf ('/');
Archivo EntryDirs = nuevo archivo (TargetFiledir + "/" + ZipEntryName.substring (0, indexNumber));
EntryDirs.mkDirs ();
EntryDirs = nulo;
} demás {
intentar {
fos = nuevo FileOutputStream (TargetFiledir + "/" + ZipEntryName);
while ((readSize = zis.read (buf, 0, file_buffer_size))! = -1) {
fos.write (Buf, 0, ReadSize);
}
} capt (excepción e) {
E.PrintStackTrace ();
tirar nueva runtimeException (e.getCause ());
} finalmente {
intentar {
if (null! = fos) {
fos.close ();
}
} Catch (ioException e) {
E.PrintStackTrace ();
tirar nueva runtimeException (e.getCause ());
}
}
}
zipEntry = zis.getNextEntry ();
}
bandera = verdadero;
} Catch (ZipException e) {
E.PrintStackTrace ();
tirar nueva runtimeException (e.getCause ());
} Catch (ioException e) {
E.PrintStackTrace ();
tirar nueva runtimeException (e.getCause ());
} finalmente {
intentar {
if (null! = zis) {
zis.close ();
}
if (null! = fos) {
fos.close ();
}
} Catch (ioException e) {
E.PrintStackTrace ();
tirar nueva runtimeException (e.getCause ());
}
}
}
Bandera de regreso;
}
/**
* Método principal para las pruebas
*/
public static void main (string [] args) {
Cadena zipFilePath = "c: // home";
Cadena zipFileName = "LP20120301.zip";
Cadena TargetFiledir = "c: // home // lp20120301";
Boolean Flag = Ziptofile.unzip (ZipFilepath, ZipFileName, TargetFiledir);
if (flag) {
System.out.println (">>>>>>> descompresión con éxito <<<<<<<<<");
} demás {
System.out.println (">>>>>>> La descompresión falló <<<<<<<");
}
}
}