「Java」Base64 エンコード デコード

JavaBase64エンコード/デコードを行なうサンプル作ってみたのでメモ。
Apache Commons Codec 1.8 を使ってやりました。

・Codec - Home
http://commons.apache.org/proper/commons-codec/

Base64 (Apache Commons Codec 1.10-SNAPSHOT API)
http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html

■ 文字列のエンコード/デコード

import org.apache.commons.codec.binary.Base64;

public class Base64Test {
	public static void main(String[] args) {
		byte[] data = "ABCDEFG".getBytes();
		
		String encodeResult = Base64.encodeBase64String(data);
		System.out.println(encodeResult);
		
		byte[] b = Base64.decodeBase64(encodeResult);
		String decodeResult = new String(b);
		System.out.println(decodeResult);
	}
}


■ ファイルのエンコード/デコード

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;

public class Base64Test {
	public static void main(String[] args) throws FileNotFoundException, IOException {
		File file = new File("input.txt");
		int fileLen = (int)file.length();
		byte[] data = new byte[fileLen];
		FileInputStream fis = new FileInputStream(file);
		fis.read(data);
		String encodeResult = Base64.encodeBase64String(data);
		System.out.println(encodeResult);

		byte[] data2 = Base64.decodeBase64(encodeResult);
		FileOutputStream fos = new FileOutputStream("output.txt");
		fos.write(data2);
	}
}

( Base64 が目的なので、例外処理は適当、ストリームのクローズもなし )


さすがライブラリって感じでした。
今度は Base64アルゴリズム部分、自分で実装してみたいなぁ・・・

以上です。