Codec入门

Codec 提供了一些公共的编解码实现,比如Base64, Hex, MD5等等。

工具类

 1 package com.cxl.beanutil.util;
 2 
 3 import org.apache.commons.codec.binary.Base64;
 4 import org.apache.commons.codec.digest.DigestUtils;
 5 
 6 import java.io.FileInputStream;
 7 import java.io.IOException;
 8 import java.io.UnsupportedEncodingException;
 9 
10 /**
11  *
12  *Codec提供了一些公共的编码实现
13  */
14 public class Codec {
15 
16     /**
17      * 计算字符串的MD5
18      * @param str
19      * @return
20      */
21     public static String strMD5(String str) {
22         str = DigestUtils.md5Hex(str);
23         System.out.println(str);
24         return str;
25     }
26 
27     /**
28      * 文件的MD5
29      * @param path
30      * @return
31      */
32     public static String fileMD5(String path) {
33         try {
34             String str = DigestUtils.md5Hex(new FileInputStream(path));
35             System.out.println(str);
36             return str;
37         } catch (IOException e) {
38             e.printStackTrace();
39         }
40         return "";
41     }
42 
43     /**
44      * 编码
45      * @param string
46      * @return
47      */
48     public static String encode(String string) {
49         Base64 base64 = new Base64();
50         try {
51             string = base64.encodeToString(string.getBytes("utf-8"));
52             System.out.println("Base64 编码后:" + string);
53         } catch (UnsupportedEncodingException e) {
54             e.printStackTrace();
55         }
56         return string;
57     }
58 
59     /**
60      * 解码
61      * @param string
62      */
63     public static void decode(String string) {
64         Base64 base64 = new Base64();
65         string = new String(base64.decode(string));
66         System.out.println("Base 解码后:" + string);
67     }
68 }

测试类

 1 package com.cxl.beanutil.test;
 2 
 3 import com.cxl.beanutil.util.Codec;
 4 import com.sun.tools.javac.jvm.Code;
 5 
 6 /**
 7  * Created by chaixinli on 2017/9/26.
 8  */
 9 public class TestCodec {
10 
11     public static void main(String[] args) {
12         Codec.encode("doudou");
13         Codec.decode("ZG91ZG91");
14 
15         Codec.strMD5("doudou");
16         Codec.fileMD5("/Users/doudou/Downloads/service.sh");
17     }
18 }

引入jar包

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.10</version>
    </dependency>

 

posted @ 2017-09-26 09:50  菲儿飞飞  Views(458)  Comments(0Edit  收藏  举报