java中BASE64编码实例

来源:互联网 发布:中国网络自由度 编辑:程序博客网 时间:2024/05/17 06:40
转自http://ajava.org/course/java/17374.html
核心提示:java Base64编码非常容易,jdk本身就提供了base64编码的类,下面是base64编码和解码的例子 例子中使用参数-e表示加密,-d表示解密. 代码 import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import sun.m

java Base64编码非常容易,jdk本身就提供了base64编码的类,下面是base64编码和解码的例子

例子中使用参数-e表示加密,-d表示解密.

代码
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

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


public class Base64 {

    
/**
     * 
@param args
     
*/
    
public static void main(String[] args) throws Exception {
        
// TODO Auto-generated method stub        
        if(args.length==2){
            
if("-e".equals(args[1])){
                //System.out.println(
"encoding./r/n/r/n");
                BASE64Encoder base64
=new BASE64Encoder();
                base64.encode(args[
0].getBytes("utf-8"), System.out);
            }
else if("-d".equals(args[1])){
                //System.out.println(
"decoding./r/n/r/n");
                BASE64Decoder base64
=new BASE64Decoder();
                base64.decodeBuffer(
new ByteArrayInputStream(args[0].getBytes("utf-8")), System.out);
            }
        }
else if(args.length==3){
            
if("-e".equals(args[2])){
                //System.out.println(
"encoding./r/n/r/n");
                BASE64Encoder base64
=new BASE64Encoder();
                base64.encode(
new FileInputStream(args[0]), new FileOutputStream(args[1],false));
            }
else if("-d".equals(args[2])){
                //System.out.println(
"decoding./r/n/r/n");
                BASE64Decoder base64
=new BASE64Decoder();
                base64.decodeBuffer(
new FileInputStream(args[0]), new FileOutputStream(args[1],false));
            }
        }
else 
            System.out.println(
"used c://>java Base64 inputString -e or c://>java Base64 inputFile outputFile -d");
        System.out.flush();
        System.out.println(
"/r/n/r/n");
    }

}

 轻松完成了字符串的编码解码以及文件的编码解码

了解Base64,请  http://zh.wikipedia.org/wiki/Base64
原创粉丝点击