先來實現一個簡單的單文件壓縮,主要是為了解一下壓縮需要使用到的流。。
效果:
說明:壓縮實現使用ZipOutputStream
代碼:
package com.gx.compress;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
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;/**
* @ClassName: CompressUtil
* @Description: 壓縮單個文件
* @author zhoujie
* @date 2018年7月29日 下午9:56:29
* @version V1.0*/
public class CompressUtil {static String path = "F:\\圖片\\"; //文件夾路徑public static void main(String[] args) {String filePath = path + "銅錢.jpg"; //圖片名稱String outPath = path + "new.zip"; //壓縮文件名稱地址zipUtil(filePath, outPath); //壓縮}public static void zipUtil(String filePath, String outPath){//輸入File file = null;FileInputStream fis = null;BufferedInputStream bin = null;DataInputStream dis = null;//輸出File outfile = null;FileOutputStream fos = null;BufferedOutputStream bos = null;ZipOutputStream zos = null;ZipEntry ze = null;try {//輸入-獲取數據file = new File(filePath);fis = new FileInputStream(file);bin = new BufferedInputStream(fis);dis = new DataInputStream(bin); //增強//輸出-寫出數據outfile = new File(outPath);fos = new FileOutputStream(outfile); bos = new BufferedOutputStream(fos, 1024); //the buffer sizezos = new ZipOutputStream(bos); //壓縮輸出流ze = new ZipEntry(file.getName()); //實體ZipEntry保存zos.putNextEntry(ze);int len = 0;//臨時文件byte[] bts = new byte[1024]; //讀取緩沖while((len=dis.read(bts)) != -1){ //每次讀取1024個字節System.out.println(len);zos.write(bts, 0, len); //每次寫len長度數據,最后前一次都是1024,最后一次len長度}System.out.println("壓縮成功");} catch (Exception e) {e.printStackTrace();} finally{try { //先實例化后關閉zos.closeEntry();zos.close();bos.close();fos.close();dis.close();bin.close();fis.close();} catch (IOException e) {e.printStackTrace();}}}}
以上僅為單個文件壓縮,了解壓縮流程。
下面這個是支持 單文件 或 文件夾 壓縮:
java 實現壓縮文件(單文件 或 文件夾)
ok。