Base64编码的Java语言实现

 static String BaseTable[] = { 
"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","+","/" 
}; 


public static void encode(String filename, BufferedWriter out) { 
try { 
File f = new File(filename); 
FileInputStream fin = new FileInputStream(filename); 

// 读文件到BYTE数组 
byte bytes[] = new byte[(int)(f.length())]; 
int n = fin.read(bytes); 

if (n < 1) return; // 没有内容 

byte buf[] = new byte[4]; // base64 字符数组 

int n3byt = n / 3; // 3 bytes 组数 
int nrest = n % 3; // 分组后剩余 bytes 
int k = n3byt * 3; // 
int linelength = 0; // 行长 
int i = 0; // 指针 

// 3-bytes 分组 ... 
while ( i < k ) { 
buf[0] = (byte)(( bytes[i] & 0xFC) >> 2); 
buf[1] = (byte)(((bytes[i] & 0x03) << 4) | 
((bytes[i+1] & 0xF0) >> 4)); 
buf[2] = (byte)(((bytes[i+1] & 0x0F) << 2) | 
((bytes[i+2] & 0xC0) >> 6)); 
buf[3] = (byte)( bytes[i+2] & 0x3F); 
send(out, BaseTable[buf[0]]); 
send(out, BaseTable[buf[1]]); 
send(out, BaseTable[buf[2]]); 
send(out, BaseTable[buf[3]]); 
/* 
以上代码可以优化,但会难以理解 
buf[0]= (byte)(b[i] >> 2); 
buf[1]= (byte)(((b[i] & 0x03) << 4)|(b[i+1]>> 4)); 
buf[2]= (byte)(((b[i+1] & 0x0F)<< 2)|(b[i+2]>> 6)); 
buf[3]= (byte)(b[i+2] & 0x3F); 
send(out,BaseTable[buf[0]]+BaseTable[buf[1]]+ 
BaseTable[buf[2]]+BaseTable[buf[3]]); 
*/ 

if ((linelength += 4) >= 76) { 
send(out, " "); 
linelength = 0; 

i += 3; 


// 处理尾部 ... 
if (nrest==2) { 
// 2 bytes left 
buf[0] = (byte)(( bytes[k] & 0xFC) >> 2); 
buf[1] = (byte)(((bytes[k] & 0x03) << 4) | 
((bytes[k+1] & 0xF0) >> 4)); 
buf[2] = (byte)(( bytes[k+1] & 0x0F) << 2); 

else if (nrest==1) { 
// 1 byte left 
buf[0] = (byte)((bytes[k] & 0xFC) >> 2); 
buf[1] = (byte)((bytes[k] & 0x03) << 4); 

if (nrest > 0) { 
// 发送尾部 
if ((linelength += 4) >= 76) send(out, " "); 
send(out, BaseTable[buf[0]]); 
send(out, BaseTable[buf[1]]); 
// 
if (nrest==2) { 
send(out, BaseTable[buf[2]]); 

else { 
send(out, "="); 

send(out, "="); 

out.flush(); 
//这里用到的send方法,请大家根据需要,自己写。可以是把结果输出到控制台,或发送邮件。 

catch (Exception e) { 
e.printStackTrace(); 


} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值