1. 程式人生 > >Base64編碼實現一---使用sun.misc.BASE64Encoder實現Base64

Base64編碼實現一---使用sun.misc.BASE64Encoder實現Base64

使用sun.misc.BASE64Encoder實現Base64

package com.zero.io.base64;

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 sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 使用sun.misc.BASE64Encoder實現Base64
 *
 */
public class BASE64EncoderTest {

	public static void main(String[] args) throws Exception {
		encode("src/pexels_photo.jpeg");//11M
		byte [] b = decode(encode("src/pexels_photo.jpeg"));
		
		createBase64File("D://sun_misc_base64.jpeg",b);
		
	}

	/**
	 * 將文字轉為字串
	 * @param filePath 檔案的路徑
	 * @return String
	 * @throws Exception
	 */
	private static String encode(String filePath)  {
		BufferedInputStream inputStream = null;
		byte [] b = null;
		try {
			inputStream = new BufferedInputStream(new FileInputStream(filePath));
			b = new byte [inputStream.available()];
			inputStream.read(b);
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != inputStream){
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return new BASE64Encoder().encode(b);
	}
	
	/**
	 * 將字串轉為byte[]陣列
	 * @param fileString 檔案使用encode方法轉成的字串資料
	 * @return byte []
	 * @throws Exception 
	 */
	private static byte [] decode(String fileString) {
		byte [] b = null;	
		try {
			b =  new BASE64Decoder().decodeBuffer(fileString);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return b;
	}
	
	/**
	 * 生成檔案
	 * @param filepath 檔案路徑
	 * @param b
	 * @return
	 */
	public static boolean createBase64File(String filepath,byte [] b){
		
		BufferedOutputStream bufferedOutputStream = null;
		File file = null;
		try {
			file = new File(filepath);
			
			if (file.exists() && file.isFile()) {
				file.delete();
			}
			
			bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
			bufferedOutputStream.write(b);
			bufferedOutputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (null != bufferedOutputStream) {
				try {
					bufferedOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
	}

}