Base64的使用,解碼和編碼

來源:互聯網
上載者:User

Java Base64 這是一個用於編碼和解碼(encode/decode )base64字串和資料流的Java開源類庫。Base64是網路上最常見的用於傳輸8Bit位元組代碼的編碼方式之一。可用來作為電子郵件或WebService附件的傳輸編碼.


使用方法:
  把類庫 javabase64-1.2.jar 設定到編譯路徑中。
  
範例程式碼:
    String類型 進行Base64編碼
    String encoded = Base64.encode("Hello, world!");
    
    String類型 進行Base64解碼
    String decoded = Base64.decode(encoded);
    
    指定字元編碼方式
    String encoded = Base64.encode("Hello, world!", "UTF-8");    
    String decoded = Base64.decode(encoded, "UTF-8");    

對檔案進行編碼:
如果檔案比較小,可以通過以下方式,直接讀取到記憶體中進行編碼處理

byte[] source = ...; // load your data here
byte[] encoded = Base64.encode(source);
byte[] decoded = Base64.decode(encoded);

如果大件比較大,則建議使用stream:
程式碼範例Base64編碼:
InputStream inputStream = new FileInputStream("source.jpg");
OutputStream outputStream = new FileOutputStream("encoded.b64");
Base64.encode(inputStream, outputStream);
outputStream.close();
inputStream.close();

程式碼範例Base64解碼:

InputStream inputStream = new FileInputStream("encoded.b64");
OutputStream outputStream = new FileOutputStream("decoded.jpg");
Base64.decode(inputStream, outputStream);
outputStream.close();

inputStream.close();

Java Base64 項目網址: http://www.sauronsoftware.it/projects/javabase64/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.