jdk8开始已经含有base64编解码方法。这里是针对jdk7的实现,使用方法:Base64Encoder.encode(String str);
package mybase64.encrypt;
import java.io.*;
class Base64Encoder extends FilterOutputStream {
private static final char[] chars = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/'
};
private int charCount;
private int carryOver;
/***
* Constructs a new Base64 encoder that writes output to the given
* OutputStream.
*
* @param out the output stream
*/
public Base64Encoder(OutputStream out) {
super(out);
}
/***
* Writes the given byte to the output stream in an encoded form.
*
* @exception IOException if an I/O error occurs
*/
public void write(int b) throws IOException {
// Take 24-bits from three octets, translate into four encoded chars
// Break lines at 76 chars
// If necessary, pad with 0 bits on the right at the end
// Use = signs as padding at the end to ensure encodedLength % 4 == 0
// Remove the sign bit,
// thanks to Christian Schweingruber