base64変換の一覧とその詳細サンプルコード

Javaには、標準でBase64のエンコード・デコード処理を行うメソッドはありません。

sun.misc.BASE64Encoderは、Javaのバージョンや Sun 以外の VM には存在しない可能性があるので、互換性を考慮すると使用しない方がよいとされています。
ビルド時にも警告が出ます。

警告:sun.misc.BASE64Decoder は Sun が所有する API であり、今後のリリースで削除される可能性があります。
警告:sun.misc.BASE64Encoder は Sun が所有する API であり、今後のリリースで削除される可能性があります。

sun.misc.BASE64Encoder sun.misc.BASE64Decoderの例
org.apache.commons.codec.binary.Base64の例
Base64.javaの例
その他

Base64エンコードの仕様

RFC2045
RFC3548

Androidでは2.2よりandroid.util.Base64が組み込まれています。
android.util.Base64

sun.misc.BASE64Encoder sun.misc.BASE64Decoderの例

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

// BASE64変換
public static String decodeBase64(byte[] buf){
  try{
    return (new BASE64Encoder()).encode(buf);
  } catch (IOException e) {
  }
  return null;
}

// BASE64逆変換
public static byte[] decodeBase64(String str){
  try{
    return (new BASE64Decoder()).decodeBuffer(str);
  } catch (IOException e) {
  }
  return null;
}

org.apache.commons.codec.binary.Base64の例

org.apache.commons.codec.binary.Base64
Commons Codec

// BASE64変換
public static String decodeBase64(byte[] buf){
  return Base64.encodeBase64(buf);
}

// BASE64逆変換
public static byte[] decodeBase64(byte[] buf){
  return Base64.decodeBase64(buf);
}

Base64.javaの例

http://iharder.net/base64
Base64.java

// BASE64変換
public static String decodeBase64(byte[] buf){
  return Base64.encodeBytes(buf);
}

// BASE64逆変換
public static byte[] decodeBase64(byte[] buf){
  try {
    return Base64.decode(buf);
  } catch (IOException e) {

  }
  return null;
}

その他

import javax.mail.MessagingException;
import javax.mail.internet.MimeUtility;

関連記事

スポンサーリンク

string_format修飾子 フォーマット(整形)して表示する

ホームページ製作・web系アプリ系の製作案件募集中です。

上に戻る