Apache Commons:Commons-codec介绍

http://www.zihou.me/html/2011/03/23/2983.html

 

在实际的应用中,我们经常需要对字符串进行编解码,Apache Commons家族中的Commons Codec就提供了一些公共的编解码实现,比如Base64, Hex, MD5,Phonetic and URLs等等。

一、官方网址

http://commons.apache.org/codec/

二、例子

1、  Base64编解码

private static String encodeTest(String str){

Base64 base64 = new Base64();

try {

str = base64.encodeToString(str.getBytes(“UTF-8″));

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

System.out.println(“Base64 编码后:”+str);

return str;

}

 

private static void decodeTest(String str){

Base64 base64 = new Base64();

//str = Arrays.toString(Base64.decodeBase64(str));

str = new String(Base64.decodeBase64(str));

System.out.println(“Base64 解码后:”+str);

}

2、 Hex编解码

private static String encodeHexTest(String str){

try {

str = Hex.encodeHexString(str.getBytes(“UTF-8″));

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

System.out.println(“Hex 编码后:”+str);

return str;

}

 

private static String decodeHexTest(String str){

Hex hex = new Hex();

try {

str = new String((byte[])hex.decode(str));

} catch (DecoderException e) {

e.printStackTrace();

}

System.out.println(“Hex 编码后:”+str);

return str;

}

3、 MD5加密

private static String MD5Test(String str){

try {

System.out.println(“MD5 编码后:”+new String(DigestUtils.md5Hex(str.getBytes(“UTF-8″))));

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return str;

}

4、  SHA编码

private static String ShaTest(String str){

try {

System.out.println(“SHA 编码后:”+new String(DigestUtils.shaHex(str.getBytes(“UTF-8″))));

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return str;

}

5、 Metaphone和Soundex

这个例子来源于网上,网址见:

http://350129923.blog.163.com/blog/static/17959113200763144659125/

Metaphone 建立出相同的key给发音相似的单字, 比 Soundex 还要准确, 但是 Metaphone 没有固定长度, Soundex 则是固定第一个英文字加上3个数字. 这通常是用在类似音比对, 也可以用在 MP3 的软件开发.

import org.apache.commons.codec.language.*;
import org.apache.commons.codec.*;

public class LanguageTest {

public static void main(String args[]) {
Metaphone metaphone = new Metaphone();
RefinedSoundex refinedSoundex = new RefinedSoundex();
Soundex soundex = new Soundex();

for (int i=0; i<2; i++ ) {
String str=(i==0)?”resume”:”resin”;

String mString = null;
String rString = null;
String sString = null;

try {
mString = metaphone.encode(str);
rString = refinedSoundex.encode(str);
sString = soundex.encode(str);

} catch (Exception ex) {
;
}
System.out.println(“Original:”+str);
System.out.println(“Metaphone:”+mString);
System.out.println(“RefinedSoundex:”+rString);
System.out.println(“Soundex:”+sString +”\\n”);

}
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值