Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to implement a compressed package tool class in java

Shulou Source: shulou.com Published: 2022-06-02 08:35:06 10月03日 Update

This article introduces you how to achieve a compressed package tool class in java, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Package com.tools;import java.io.*;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;public class ZipCompress {private String zipFileName; private String sourceFileName; public ZipCompress (String zipFileName, String sourceFileName) {this.zipFileName = zipFileName; this.sourceFileName = sourceFileName;} public void zip () throws RuntimeException {ZipOutputStream zos = null; try {zos = new ZipOutputStream (new FileOutputStream (zipFileName)) Java.io.File sourceFile = new java.io.File (sourceFileName); compress (sourceFile, zos, sourceFile.getName ()); System.out.println ("Compression complete");} catch (Exception e) {throw new RuntimeException ("zip error from ZipCompress", e) } finally {if (zos! = null) {try {zos.close ();} catch (IOException e) {e.printStackTrace () }} / * * Recursive compression method * * @ param sourceFile source file * @ param zos zip output stream * @ param name compressed name * @ throws Exception * / private static void compress (java.io.File sourceFile, ZipOutputStream zos String name) throws Exception {byte [] buf = new byte [2 * 1024] If (sourceFile.isFile ()) {zos.putNextEntry (new ZipEntry (name)); int len; FileInputStream in = new FileInputStream (sourceFile); while ((len = in.read (buf))! =-1) {zos.write (buf, 0, len);} zos.closeEntry (); in.close () } else {java.io.File [] listFiles = sourceFile.listFiles (); if (listFiles = = null | | listFiles.length = = 0) {zos.putNextEntry (new ZipEntry (name + "/")); zos.closeEntry () } else {for (java.io.File file: listFiles) {compress (file, zos, name + "/" + file.getName ());}

Call

/ / filePath generates the address of the compressed package String filePath = prefix address + name + ".zip"; File zip = new File (filePath); zip.deleteOnExit (); / / path folder to be compressed ZipCompress zipCompress = new ZipCompress (filePath, path); try {zipCompress.zip ();} catch (Exception e) {e.printStackTrace () } on how to achieve a compressed package tool class in java to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Tools content name address more help good interest prefix guys buddies files folders articles methods source files knowledge articles recursion reference Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Linux vpn Microsoft macOS