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”);
}
}
}
總結
以上是生活随笔為你收集整理的Apache Commons:Commons-codec介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Apache Commons:Betwi
- 下一篇: 使用javassist动态注入代码