Apache Commons:Commons-codec介绍
http://www.zihou.me/html/2011/03/23/2983.html
?
在實(shí)際的應(yīng)用中,我們經(jīng)常需要對(duì)字符串進(jìn)行編解碼,Apache Commons家族中的Commons Codec就提供了一些公共的編解碼實(shí)現(xiàn),比如Base64, Hex, MD5,Phonetic and URLs等等。
一、官方網(wǎng)址:
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
這個(gè)例子來(lái)源于網(wǎng)上,網(wǎng)址見(jiàn):
http://350129923.blog.163.com/blog/static/17959113200763144659125/
Metaphone 建立出相同的key給發(fā)音相似的單字, 比 Soundex 還要準(zhǔn)確, 但是 Metaphone 沒(méi)有固定長(zhǎng)度, Soundex 則是固定第一個(gè)英文字加上3個(gè)數(shù)字. 這通常是用在類似音比對(duì), 也可以用在 MP3 的軟件開(kāi)發(fā).
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”);
}
}
}
總結(jié)
以上是生活随笔為你收集整理的Apache Commons:Commons-codec介绍的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Apache Commons:Betwi
- 下一篇: 使用javassist动态注入代码