Base64編碼實現三---使用com.sun.org.apache.xerces.internal.impl.dv.util.Base64實現Base64
阿新 • • 發佈:2019-02-03
使用com.sun.org.apache.xerces.internal.impl.dv.util.Base64實現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 com.sun.org.apache.xerces.internal.impl.dv.util.Base64; /** * 使用com.sun.org.apache.xerces.internal.impl.dv.util.Base64實現Base64 * */ public class BASE64EncoderTest3 { public static void main(String[] args) throws Exception { encode("src/pexels_photo.jpeg");//11M byte [] b = decode(encode("src/pexels_photo.jpeg")); createBase64File("D://apache_xerces_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 Base64.encode(b); } /** * 將字串轉為byte[]陣列 * @param fileString 檔案使用encode方法轉成的字串資料 * @return * @throws Exception */ private static byte [] decode(String fileString) { return Base64.decode(fileString); } /** * 生成檔案 * @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(); bufferedOutputStream.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }