The third-party jar is used for compression. The following describes how to use the built-in jdk for compression:
Test:
Package com. home; import java. io. IOException; public class Test {public Test () {try {ZipUtil. doZip ("D: // test", "D: // test1.zip"); // compress the entire file to ZipUtil. doZip ("D: // test.doc", "D: // test2.zip"); // compress a single file} catch (IOException e) {e. printStackTrace () ;}} public static void main (String [] args) {new Test ();}}
ZipUtil:
Package com. home; 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.util.zip. zipEntry; import java.util.zip. zipOutputStream; public class ZipUtil {/*** compressed interface ** @ param src * full source file path * @ param des * full target zip file path * @ throws IOException */public static void doZip (Str Ing src, String des) throws IOException {File srcFile = new File (src); // source File zipFile = new File (des); // target zip File ZipOutputStream zos = null; try {zos = new ZipOutputStream (new BufferedOutputStream (new FileOutputStream (zipFile); String basePath = null; if (srcFile. isDirectory () {basePath = srcFile. getPath ();} else {basePath = srcFile. getParent ();} zipFile (srcFile, basePath, zos);} finally {if (zos! = Null) {zos. closeEntry (); zos. close () ;}}/*** compressed File ** @ param srcFile * @ param basePath * @ param zos * @ throws IOException */private static void zipFile (File srcFile, string basePath, ZipOutputStream zos) throws IOException {File [] files = null; if (srcFile. isDirectory () {files = srcFile. listFiles ();} else {files = new File [1]; files [0] = srcFile;} BufferedInputStream bis = null; String pathName; byte [] Buf = new byte [1024]; int len = 0; try {for (File file: files) {if (file. isDirectory () {if (! BasePath. endsWith ("\") {basePath + = "\";} pathName = file. getPath (). substring (basePath. length () + "\"; zos. putNextEntry (new ZipEntry (pathName); zipFile (file, basePath, zos);} else {if (! BasePath. endsWith ("\") {basePath + = "\";} pathName = file. getPath (). substring (basePath. length (); bis = new BufferedInputStream (new FileInputStream (file); zos. putNextEntry (new ZipEntry (pathName); while (len = bis. read (buf)> 0) {zos. write (buf, 0, len) ;}}} finally {if (bis! = Null) {bis. close ();}}}}