ZIP加密文件轉字符串存儲工具類

公司喜歡把文件用字符串的形式存儲到存儲引擎,以前沒有接觸過,學習了下Base64編碼,解碼。還有zip流的使用,自己寫的註釋很全,有什麼問題歡迎評論討論。

package com.etaxserver.util;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;

/**
 * 把文件數據  轉換成字符串
 */
public class ZipUtil {

	private static final Logger logger = LoggerFactory.getLogger(ZipUtil.class);
	/**
	 * 壓縮加密(zip壓縮,base64加密) : Base64編碼,是我們程序開發中經常使用到的編碼方法。它是一種基於用64個可打印字符來表示二進制數據的表示方法。它通常用作存儲、傳輸一些二進制數據編碼方法
	 * Base64加密後的數據量是原來的4/3
	 * (先壓縮、在base64加密)
	 * @param str
	 * @param iszip	判斷是否zip壓縮, false表示只做base64操作
	 * @return
	 */
	public static String zipEncode(String str,boolean iszip){
		String encodeStr="";
		try{
			if(iszip){
				// 使用ZIP壓縮
				encodeStr=new sun.misc.BASE64Encoder().encodeBuffer(compress(str));
			}
			else{
				// 簡單的獲得String 字節組
				encodeStr=new sun.misc.BASE64Encoder().encodeBuffer(str.getBytes("UTF-8")).trim();
			}
			if(null!=encodeStr){
				// 去除多餘
				encodeStr = encodeStr.replaceAll("\r\n", "").replaceAll("\n","");
			}
		}catch(Exception e){
			logger.error("壓縮加密失敗:"+str,e);
			e.printStackTrace();
		}
		return encodeStr;
	}
	/**
	 * 解密(壓縮解密)
	 * (先base64解密,在解壓)
	 * @param zipStr
	 * @param iszip	是否是壓縮文件, false表示只做base64操作
	 * @return
	 */
	public static String unzipDecode(String zipStr,boolean iszip) {
		String unzipStr="";
		try{
			// 先解碼
			byte[] unzip=new sun.misc.BASE64Decoder().decodeBuffer(zipStr);
			if(iszip){
				// ZIP解壓
				unzipStr=decompress(unzip);
			}
			else{
				// String 解碼
				unzipStr= new String(unzip,"UTF-8");
			}
		}
		catch(Exception e){
			logger.error("壓縮解密失敗:"+zipStr);
			e.printStackTrace();
		}
		return unzipStr;
	}
	/**
	 * 壓縮
	 * 
	 * 這裏需要特別注意的是,如果你想把壓縮後的byte[]保存到字符串中,
	 * 不能直接使用new String(byte)或者byte.toString(), 因爲這樣轉換之後容量是增加的。
	 * 同樣的道理,如果是字符串的話,也不能直接使用new String().getBytes()獲取byte[]傳入到decompress中進行解壓縮。
	 * 如果保存壓縮後的二進制,可以使用new sun.misc.BASE64Encoder().encodeBuffer(byte[] b)將其轉換爲字符串。
	 * 同樣解壓縮的時候首先使用new BASE64Decoder().decodeBuffer 方法將字符串轉換爲字節,然後解壓就可以了。
     *
	 * @param str
	 * @return
	 */
	private static byte[] compress(String str) {
		if (str == null)
			return null;

		byte[] compressed;
		// 內存字節流
		ByteArrayOutputStream out = null;
		// 以ZIP定義的格式的輸出流
		ZipOutputStream zout = null;

		try {
			out = new ByteArrayOutputStream();
			// 看出 是個包裝類
			zout = new ZipOutputStream(out);
			// ZipEntry 定義ZIP的修改時間、位置等信息
			// name 不知道什麼作用
			zout.putNextEntry(new ZipEntry("0"));
			zout.write(str.getBytes("UTF-8"));
			zout.closeEntry();
			//獲取壓縮字節
			compressed = out.toByteArray();
		} catch (IOException e) {
			compressed = null;
		} finally {
			if (zout != null) {
				try {
					zout.close();
				} catch (IOException e) {
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}

		return compressed;
	}

	/**
	 * 解壓
	 * @param compressed
	 * @return
	 */
	private static String decompress(byte[] compressed) {
		if (compressed == null)
			return null;

		ByteArrayOutputStream out = null;
		ByteArrayInputStream in = null;
		ZipInputStream zin = null;
		String decompressed;
		try {
			out = new ByteArrayOutputStream();
			in = new ByteArrayInputStream(compressed);
			zin = new ZipInputStream(in);
			ZipEntry entry = zin.getNextEntry();
			byte[] buffer = new byte[1024];
			int offset = -1;
			while ((offset = zin.read(buffer)) != -1) {
				out.write(buffer, 0, offset);
			}
			decompressed = out.toString("UTF-8");
		} catch (IOException e) {
			decompressed = null;
		} finally {
			if (zin != null) {
				try {
					zin.close();
				} catch (IOException e) {
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}

		return decompressed;
	}

	/**
	 * 把圖片 轉換成字符串 存儲
	 * @param f
	 * @return
	 */
	public  static String getImageBinary(File f){      

	        BufferedImage bi;      
	        try {      
	            bi = ImageIO.read(f);      
	            ByteArrayOutputStream baos = new ByteArrayOutputStream();      
	            ImageIO.write(bi, "jpg", baos);      
	            byte[] bytes = baos.toByteArray();      

	            return new sun.misc.BASE64Encoder().encodeBuffer(bytes).trim();      
	        } catch (IOException e) {      
	            e.printStackTrace();      
	        }      
	        return null;      
	    }
	    
	public static void main(String[] args) throws IOException {
		String filePath="C:\\Program Files (x86)\\Thunder Network\\WallPaper\\Data\\Paper\\134579.jpg";
		String imageBinaryStr = getImageBinary(new File(filePath));
		byte[] bytes = new BASE64Decoder().decodeBuffer(imageBinaryStr);
		FileOutputStream fileOutputStream = new FileOutputStream("D:zcm.jpg");
		fileOutputStream.write(bytes);
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章