Uma simples classe de ferramenta de descompressão de compressão ZIP escrita usando a classe Basic Java
A cópia do código é a seguinte:
pacote sun.net.helper;
importar java.io.*;
importar java.util.logging.logger;
importar java.util.zip.*;
classe pública Ziputil {
Logger estático final privado = logger.getLogger (ziputil.class.getName ());
Buffer final estático privado Int = 1024*10;
/**
* Compressa o diretório especificado em um arquivo zip com o mesmo nome do diretório e personalize o caminho de compressão
* @Param SourceFilePath Target File Path
* @param zipfilepath especifique o caminho do arquivo zip
* @retornar
*/
public static boolean zip (String sourcefilepath, string zipfilepath) {
resultado booleano = false;
Fonte de arquivo = novo arquivo (fonteFilePath);
if (! fonte.exists ()) {
Logger.info (SourceFilePath+"não existe.");
resultado de retorno;
}
if (! fonte.isdirectory ()) {
Logger.info (SourceFilePath+"não é um diretório.");
resultado de retorno;
}
Arquivo zipfile = novo arquivo (zipFilePath+"/"+fonte.getName ()+". Zip");
if (zipfile.exists ()) {
Logger.info (zipfile.getName ()+"já existe.");
resultado de retorno;
}outro{
if (! zipfile.getParentFile (). Existe ()) {
if (! zipfile.getparentfile (). mkdirs ()) {
Logger.info ("não pode criar arquivo"+zipfile.getName ());
resultado de retorno;
}
}
}
Logger.info ("Criando arquivo zip ...");
FileOutputStream dest = null;
ZipOutputStream out = null;
tentar {
dest = new FileOutputStream (zipFile);
CheckOututputStream checkSum = new CheckedOutputStream (dest, new Adler32 ());
out = new ZipOutputStream (new BufferoudOutputStream (checksum));
out.setMethod (zipOutputStream.Deflated);
compactar (fonte, out, fonte.getName ());
resultado = true;
} catch (filenotfoundException e) {
E.PrintStackTrace ();
} finalmente {
if (out! = null) {
tentar {
out.CloseEntry ();
} catch (ioexception e) {
E.PrintStackTrace ();
}
tentar {
out.Close ();
} catch (ioexception e) {
E.PrintStackTrace ();
}
}
}
if (resultado) {
logger.info ("feito.");
}outro{
Logger.info ("Fail.");
}
resultado de retorno;
}
Compressa estática privada (arquivo de arquivo, zipOutputStream Out, string mainfilename) {
if (file.isfile ()) {
FileInputStream fi = null;
Origem bufferedInputStream = NULL;
tentar {
fi = new FileInputStream (arquivo);
origem = new bufferInputStream (fi, buffer);
int index = file.getabsolutepath (). indexOf (mainfileName);
String EntryName = FILE.GETABSOLUTEPATH (). Substring (index);
System.out.println (EntryName);
Entrada de zipentry = new Zipentry (nome de entrada);
out.putNextEntry (entrada);
byte [] dados = novo byte [buffer];
int contagem;
while ((count = origem.read (dados, 0, buffer))! = -1) {
out.write (dados, 0, contagem);
}
} catch (filenotfoundException e) {
E.PrintStackTrace ();
} catch (ioexception e) {
E.PrintStackTrace ();
} finalmente {
if (origem! = null) {
tentar {
origem.close ();
} catch (ioexception e) {
E.PrintStackTrace ();
}
}
}
} else if (file.isdirectory ()) {
Arquivo [] fs = file.listfiles ();
if (fs! = null && fs.length> 0) {
para (arquivo f: fs) {
compactar (f, out, mainfilename);
}
}
}
}
/**
* Descompacte o arquivo zip no diretório especificado.
* @param zipfile
* @param Destpath
* @retornar
*/
public static boolean Unzip (arquivo zipfile, string DestPath) {
resultado booleano = false;
if (! zipfile.exists ()) {
Logger.info (zipfile.getName ()+"não existe.");
resultado de retorno;
}
Target de arquivo = novo arquivo (DestPath);
if (! Target.Exists ()) {
if (! Target.mkdirs ()) {
Logger.info ("Não pode criar arquivo"+Target.getName ());
resultado de retorno;
}
}
String mainfilename = zipfile.getName (). Substituir (". Zip", "");
Arquivo TargetFile = novo arquivo (DestPath+"/"+MainFileName);
if (TargetFile.Exists ()) {
Logger.info (TargetFile.getName ()+"já existe.");
resultado de retorno;
}
ZipinputStream zis = null;
Logger.info ("Iniciar o arquivo unzip ...");
tentar {
FileInputStream fis = new FileInputStream (zipFile);
CheckIdInputStream checkSum = new CheckEdInputStream (fis, new adler32 ());
zis = new ZipinputStream (new bufferInputStream (verificação));
Entrada de zipentry;
while ((entradas = zis.getNextEntry ())! = null) {
int contagem;
byte dados [] = novo byte [buffer];
String EntryName = Entry.getName ();
int index = ingressname.indexof (mainfilename);
String newentryName = DestPath+"/"+Entryname.substring (index);
System.out.println (newentryName);
Arquivo temp = novo arquivo (newentryName) .getParentFile ();
if (! temp.exists ()) {
if (! temp.mkdirs ()) {
lançar a nova RunTimeException ("Criar arquivo" +temp.getName () +"Fail");
}
}
FileOutputStream fos = new FileOutputStream (newentryName);
BufferoudOutputStream dest = new BufferoudOutputStream (fos, buffer);
while ((count = zis.read (dados, 0, buffer))! = -1) {
dest.Write (dados, 0, contagem);
}
dest.flush ();
dest.close ();
}
resultado = true;
} catch (filenotfoundException e) {
E.PrintStackTrace ();
} catch (ioexception e) {
E.PrintStackTrace ();
} finalmente {
if (zis! = null) {
tentar {
zis.close ();
} catch (ioexception e) {
E.PrintStackTrace ();
}
}
}
if (resultado) {
logger.info ("feito.");
}outro{
Logger.info ("Fail.");
}
resultado de retorno;
}
public static void main (string [] args) lança ioexception {
//Ziputil.zip("d:/apache-tomcat-7.0.30 "," d:/temp ");
Arquivo zipfile = novo arquivo ("d: /temp/apache-tomcat-7.0.30.zip");
Ziputil.unzip (zipfile, "d:/temp");
}
}
Outro exemplo de compactação e descompressão, consulte as duas ferramentas.
A cópia do código é a seguinte:
pacote com.lanp;
importar java.io.file;
importar java.io.fileInputStream;
importar java.io.fileOutputStream;
importar java.io.ioException;
importar java.util.zip.zipentry;
importar java.util.zip.ziPexception;
importar java.util.zip.zipfile;
importar java.util.zip.zipinputStream;
/**
* Descompacte o arquivo compactado com zíper no diretório especificado
*/
Classe final pública ZIPTOFILE {
/**
* O tamanho do cache padrão para 20480
*/
private final static int file_buffer_size = 20480;
private ziptofile () {
}
/**
* Descompacte o arquivo compactado do zip do diretório especificado para o diretório especificado
* @param zipfilepathzip Caminho de arquivo comprimido
* @param zipfileNamezip Nome do arquivo compactado
* @param TargetFiledirzip File compactado a ser extraído
* @return slag boolean Return Value
*/
public static boolean Unzip (string zipfilepath, string zipfilename, string TargetFiledir) {
bandeira booleana = false;
// 1.
Arquivo de arquivo = null; // arquivo compactado (com caminho)
Zipfile zipfile = null;
arquivo = novo arquivo (zipFilePath + "/" + zipFileName);
System.out.println (">>>>>>> descompacte o arquivo [" + zipFilePath + "/" + zipfileName + "] no diretório [" + TargetFiledir + "] <<<<<<<<<");
if (false == file.exists ()) {
System.out.println (">>>>>>> arquivo comprimido [" + zipFilePath + "/" + zipfilename + "] não existe <<<<<<<<");
retornar falso;
} else if (0 == file.length ()) {
System.out.println (">>>>>>> arquivo comprimido [" + zipFilePath + "/" + zipfilename + "] O tamanho é 0 e não requer descompressão <<<<<<");
retornar falso;
} outro {
// 2.
byte [] buf = novo byte [file_buffer_size];
int readsize = -1;
ZipinputStream zis = null;
FileOutputStream fos = null;
tentar {
// Verifique se é um arquivo zip
zipfile = new ZipFile (arquivo);
zipfile.close ();
// Determine se o diretório de destino existe.
Arquivo newdir = novo arquivo (TargetFiledir);
if (false == newdir.exists ()) {
newdir.mkdirs ();
newdir = null;
}
zis = new ZipinputStream (new FileInputStream (arquivo));
Zipentry zipentry = zis.getNextEntry ();
// inicia o processamento de arquivos no pacote compactado
while (null! = zipentry) {
String zipentryName = zipentry.getName (). Substituir ('//', '/');
// julga se o Zipentry é um diretório
if (zipentry.isdirectory ()) {
int indexNumber = zipentryname.lastIndexof ('/');
Arquivo Entrydirs = novo arquivo (TargetFiledir + "/" + zipentryname.substring (0, indexNumber));
Entrydirs.mkdirs ();
entrada de entrada = null;
} outro {
tentar {
fos = new FileOutputStream (TargetFiledir + "/" + ZipentryName);
while ((readsize = zis.read (buf, 0, file_buffer_size))! = -1) {
fos.write (buf, 0, readsize);
}
} catch (Exceção e) {
E.PrintStackTrace ();
lançar a nova RuntimeTeException (e.getCause ());
} finalmente {
tentar {
if (null! = fos) {
fos.close ();
}
} catch (ioexception e) {
E.PrintStackTrace ();
lançar a nova RuntimeTeException (e.getCause ());
}
}
}
zipentry = zis.getNextEntry ();
}
bandeira = true;
} catch (zipexception e) {
E.PrintStackTrace ();
lançar a nova RuntimeTeException (e.getCause ());
} catch (ioexception e) {
E.PrintStackTrace ();
lançar a nova RuntimeTeException (e.getCause ());
} finalmente {
tentar {
if (null! = zis) {
zis.close ();
}
if (null! = fos) {
fos.close ();
}
} catch (ioexception e) {
E.PrintStackTrace ();
lançar a nova RuntimeTeException (e.getCause ());
}
}
}
bandeira de retorno;
}
/**
* Método principal para teste
*/
public static void main (string [] args) {
String zipfilepath = "c: // home";
String zipfilename = "lp20120301.zip";
String TargetFiledir = "C: // Home // LP20120301";
bandeira booleana = ziptofile.unzip (zipfilepath, zipfileName, TargetFiledir);
if (flag) {
System.out.println (">>>>>>> descomprimir com sucesso <<<<<<<");
} outro {
System.out.println (">>>>>>> A descompressão falhou <<<<<<");
}
}
}