Java中的zip和gzip是兩種用于文件壓縮的類庫。zip可以用于壓縮多個文件成一個文件,gzip則是用于壓縮單個文件。
Zip壓縮:
public static void createZipFile(String zipFileName, String[] fileNames) throws IOException { FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); byte[] buffer = new byte[1024]; for (String fileName : fileNames) { ZipEntry entry = new ZipEntry(fileName); zos.putNextEntry(entry); FileInputStream fis = new FileInputStream(fileName); int len; while ((len = fis.read(buffer)) >0) { zos.write(buffer, 0, len); } fis.close(); } zos.closeEntry(); zos.close(); fos.close(); }
gzip壓縮:
public static void createGzipFile(String gzipFileName, String fileName) throws IOException { FileOutputStream fos = new FileOutputStream(gzipFileName); GZIPOutputStream gzos = new GZIPOutputStream(fos); FileInputStream fis = new FileInputStream(fileName); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) >0) { gzos.write(buffer, 0, len); } fis.close(); gzos.finish(); gzos.close(); fos.close(); }
以上兩個方法均需要傳入要壓縮的文件名、壓縮后的文件名及路徑等參數。同時,需要注意輸入輸出流的關閉順序。