1. 程式人生 > 程式設計 >基於Java實現檔案和base64字串轉換

基於Java實現檔案和base64字串轉換

這篇文章主要介紹了基於Java實現檔案和base64字串轉換,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

專案中遇到需要將圖片轉成base64編碼的字串的需求,但是,考慮到擴充套件性,寫了一個可以轉換任務型別檔案的方法。需要引入的包:

    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.13</version>
    </dependency>

原始碼如下:

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
 
import java.io.*;
 
 
public class Base64FileUtil {
 
 
  private static String targetFilePath = "E:\\base2Img\\target\\test.txt";
 
 
  public static void main(String[] args) throws Exception {
    String fileStr = getFileStr("E:\\base2Img\\big test.txt");
    System.out.println("fileStr ===" + fileStr);
    System.out.println(generateFile(fileStr,targetFilePath));
    System.out.println("end");
  }
 
 
  /**
   * 檔案轉化成base64字串
   * 將檔案轉化為位元組陣列字串,並對其進行Base64編碼處理
   */
  public static String getFileStr(String filePath) {
    InputStream in = null;
    byte[] data = null;
    // 讀取檔案位元組陣列
    try {
      in = new FileInputStream(filePath);
      data = new byte[in.available()];
      in.read(data);
      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    // 對位元組陣列Base64編碼
    BASE64Encoder encoder = new BASE64Encoder();
    // 返回 Base64 編碼過的位元組陣列字串
    return encoder.encode(data);
  }
 
 
  /**
   * base64字串轉化成檔案,可以是JPEG、PNG、TXT和AVI等等
   *
   * @param base64FileStr
   * @param filePath
   * @return
   * @throws Exception
   */
  public static boolean generateFile(String base64FileStr,String filePath) throws Exception {
    // 資料為空
    if (base64FileStr == null) {
      System.out.println(" 不行,oops! ");
      return false;
    }
    BASE64Decoder decoder = new BASE64Decoder();
 
 
    // Base64解碼,對位元組陣列字串進行Base64解碼並生成檔案
    byte[] byt = decoder.decodeBuffer(base64FileStr);
    for (int i = 0,len = byt.length; i < len; ++i) {
      // 調整異常資料
      if (byt[i] < 0) {
        byt[i] += 256;
      }
    }
    OutputStream out = null;
    InputStream input = new ByteArrayInputStream(byt);
    try {
      // 生成指定格式的檔案
      out = new FileOutputStream(filePath);
      byte[] buff = new byte[1024];
      int len = 0;
      while ((len = input.read(buff)) != -1) {
        out.write(buff,len);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      out.flush();
      out.close();
    }
    return true;
  }
 
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。