Este artigo descreve as classes de ferramentas de compactação e descompressão ZIP implementadas em Java. Compartilhe -o para sua referência, como segue:
importar java.io.bufferedInputStream; importar java.io.bufferedOutputStream; importar java.io.file; importar java.io.fileInputStream; importar java.io.filenotfoundException; importar java.io.fileOutstream; importStrA.io.ioException; Importexception; java.util.enumeration; importar org.apache.tools.zip.zipentry; importar org.apache.tools.zip.zipfile; importar org.apache.tools.zip.zipoutputStream; classe pública ziputil {private static final int buffersize = 1024; /** * Compressed file* * @param zipFileName * Saved compressed package file path* @param filePath * Folder or file path that needs to be compressed* @param isDelete * Whether to delete the source file* @throws Exception */ public void zip(String zipFileName, String filePath, boolean isDelete) throws Exception { zip(zipFileName, new Arquivo (filepath), isDelete); } / ** * Arquivo compactado * * @param zipfileName * Salvo PACHO DE PACOTO COMPRESSO * @param inputfile * pasta ou arquivo que precisa ser compactado * @param isDelete * Se deve excluir o arquivo de origem * @throws excepção * / public void (string zipfilename, file inputfile, boolan ésd, boolan é o bole, o browan (string string zipfilename, o arquivo de origem * ZipOutputStream (new FileOutputStream (zipfileName)); if (! inputfile.exists ()) {tiro o novo fileNotfoundException ("nenhum arquivo a ser comprimido foi encontrado no caminho especificado!"); } zip (out, inputfile, "", iSDelete); out.Close (); } / ** * Método de compressão recursiva * * @param out * fluxo de saída de pacote compactado * @param f * arquivo a ser compactado * @param base * caminho compactado * @param isDelete * Se você deve excluir o arquivo de origem * @throws excepção * / private void zip (zipoutstream outfil. (inputfile.isdirectory ()) {// se for um arquivo de diretório [] inputFiles = inputFile.listfiles (); out.putNextEntry (nova zipentry (base + "/")); base = base.length () == 0? "": base + "/"; for (int i = 0; i <inputFiles.length; i ++) {zip (out, inputFiles [i], base+inputfiles [i] .getName (), isDelete); }} else {// se for um arquivo se (base.length ()> 0) {out.putNextEntry (new Zipentry (base)); } else {out.putNextEntry (new Zipentry (inputFile.getName ()); } FileInputStream in = new FileInputStream (inputFile); tente {int len; byte [] buff = novo byte [buffersize]; while ((len = in.read (buff))! = -1) {out.write (buff, 0, len); }} catch (ioexception e) {tiro e; } finalmente {in.close (); }} if (isDelete) {inputFile.Delete (); }} / ** * DECOMPRESS * * @param zipFilePath * compactar caminho do pacote * @param fileAvePath * pato unzip * @param isDelete * se você deve excluir o arquivo de origem * @throws excepção * / public void (trirpthath) (filevesTeThath) (fileaVeThath). Arquivo f = novo arquivo (zipFilePath); if ((! f.exists ()) && (f.length () <= 0)) {lança nova exceção ("o arquivo a ser descomprimido não existe!"); } Zipfile zipfile = new ZipFile (f); String strpath, gbkpath, strtemp; Arquivo tempfile = novo arquivo (fileAvePath); // inicia no diretório atual strpath = tempfile.getabsolutepath (); // a posição absoluta da enumeração de saída <PexiPentry> e = zipfile.getentries (); while (e.hasMoreElements ()) {org.apache.tools.zip.zipentry zipent = e.nextElement (); gbkpath = zipent.getName (); if (zipent.isdirectory ()) {strTemp = strpath + file.separator + gbkpath; Arquivo dir = novo arquivo (strTemp); Dir.mkdirs (); continuar; } else {// Leia e grava o arquivo inputStream is = zipfile.getInputStream (zipent); BufferInputStream bis = new bufferInputStream (IS); gbkpath = zipent.getName (); strTemp = strpath + file.separator + gbkpath; // Criar diretório string strsubdir = gbkpath; para (int i = 0; i <strsubdir.length (); i ++) {if (strsubdir.substring (i, i + 1) .equalsignorecase ("/")) {string temp = strpath + file.separator + strsubdir.substring (0, i); Subdir de arquivo = novo arquivo (temp); if (! subdir.exists ()) subdir.mkdir (); }} FileOutputStream fos = new FileOutputStream (strTemp); BufferOutputStream bos = new BufferoudOutputStream (Fos); int len; byte [] buff = novo byte [buffersize]; while ((len = bis.read (buff))! = -1) {bos.write (buff, 0, len); } bos.close (); fos.close (); }}} catch (Exceção e) {e.printStackTrace (); jogar e; } if (isDelete) {new File (zipFilePath) .Delete (); }} // public static void main (string [] args) {// ziputil cpr = new ziputil (); // try {// cpr.zip ("c:/users/lenovo user/desktop/test chines.zip", "c:/usersing/lenovo user/desktop/newrop") Usuário/desktop/teste chinês.zip "," C:/Users/Lenovo User/Desktop/New Pasta 2 ", false); //} catch (Exceção e) {// e.printStacktrace (); //} /////}}Para obter mais informações sobre os algoritmos Java, os leitores interessados neste site podem visualizar os tópicos: "Resumo dos arquivos Java e habilidades de operação de diretório", "Tutorial sobre estruturas e algoritmos de dados Java e algoritmos", "Resumo das habilidades da operação Java Dom Node" e "Summary of Java cache Operação Skills"
Espero que este artigo seja útil para a programação Java de todos.