加藤 (2010年9月23日 10:00) 産業システム部
public static void main(String[] args) { String sInTestStr = "あいうえお"; byte[] inTestStrByte = sInTestStr.getBytes(); // 文字列をBase64にエンコード String sOutTestStr = Base64Util.encode(inTestStrByte); // Base64にエンコードした結果を出力 System.out.println(sOutTestStr); // Base64にエンコードした結果をデコード inTestStrByte = Base64Util.decode(sOutTestStr); // デコードした結果を出力 sInTestStr = new String(inTestStrByte); System.out.println(sInTestStr); }
public static void main1(String[] args) { String sInTestStr = "あいうえお"; byte[] inTestStrByte = sInTestStr.getBytes(); // 文字列をBase64にエンコード byte[] outTestStrBtye = Base64.encodeBase64(inTestStrByte); // Base64にエンコードした結果を出力 String sOutTestStr = new String(outTestStrBtye); System.out.println(sOutTestStr); // Base64にエンコードした結果をデコード outTestStrBtye = sOutTestStr.getBytes(); inTestStrByte = Base64.decodeBase64(outTestStrBtye); // デコードした結果を出力 sInTestStr = new String(inTestStrByte); System.out.println(sInTestStr); }
JavaでBase64エンコード/デコード処理を行う
加藤 (2010年9月23日 10:00)
産業システム部
産業システム部の加藤です。
今回は、JavaでBase64エンコード/デコード処理を行う方法について紹介します。
Javaには、標準でBase64のエンコード/デコード処理が存在しません。
ネットで検索すると引っ掛かる「sun.misc.BASE64Encoder」を使用する方法がありますが、
このクラスは、Javaのバージョンや Sun 以外の VM には存在しない可能性があるので、
通常、使用しない方がよいとされているものです。
そういった意味で、Javaには、標準でBase64のエンコード/デコード処理が存在しないことになります。
JavaでBase64エンコード/デコード処理を行うには、様々な選択肢があります。
お勧めというわけではありませんが、過去に、私が選択した方法を紹介します。
・Seasar2(S2Container)に含まれている「org.seasar.framework.util.Base64Util」を使用する方法
・Commons Codecに含まれている「org.apache.commons.codec.binary.Base64」を使用する方法
・独自に実装する方法
etc
ちなみに、独自に実装するという選択肢は、
興味本位で行ったものなのでメリットはないと思います。
最近はSeasar2をベースとしたフレームワークを利用する機会が多いので、
Seasar2の機能を利用することが多いです。
以前は、Commons Codecを利用していました。
以下に、簡単なサンプルをコードを載せておきます。
Seasar2(S2Container)に含まれている「org.seasar.framework.util.Base64Util」を使用する例
public static void main(String[] args) { String sInTestStr = "あいうえお"; byte[] inTestStrByte = sInTestStr.getBytes(); // 文字列をBase64にエンコード String sOutTestStr = Base64Util.encode(inTestStrByte); // Base64にエンコードした結果を出力 System.out.println(sOutTestStr); // Base64にエンコードした結果をデコード inTestStrByte = Base64Util.decode(sOutTestStr); // デコードした結果を出力 sInTestStr = new String(inTestStrByte); System.out.println(sInTestStr); }Commons Codecに含まれている「org.apache.commons.codec.binary.Base64」を使用する例
public static void main1(String[] args) { String sInTestStr = "あいうえお"; byte[] inTestStrByte = sInTestStr.getBytes(); // 文字列をBase64にエンコード byte[] outTestStrBtye = Base64.encodeBase64(inTestStrByte); // Base64にエンコードした結果を出力 String sOutTestStr = new String(outTestStrBtye); System.out.println(sOutTestStr); // Base64にエンコードした結果をデコード outTestStrBtye = sOutTestStr.getBytes(); inTestStrByte = Base64.decodeBase64(outTestStrBtye); // デコードした結果を出力 sInTestStr = new String(inTestStrByte); System.out.println(sInTestStr); }参考:Seasar2(S2Container)
http://s2container.seasar.org/2.4/ja/
参考:Commons Codec
http://commons.apache.org/codec