第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > Apache Commons:Commons-codec介绍

Apache Commons:Commons-codec介绍

时间:2023-12-14 16:34:35

相关推荐

Apache Commons:Commons-codec介绍

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

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

一、官方网址

/codec/

二、例子

1、 Base64编解码

private staticString encodeTest(String str){

Base64 base64 =newBase64();

try{

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

}catch(UnsupportedEncodingException e) {

e.printStackTrace();

}

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

returnstr;

}

private static voiddecodeTest(String str){

Base64 base64 =newBase64();

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

str =newString(Base64.decodeBase64(str));

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

}

2、 Hex编解码

private staticString encodeHexTest(String str){

try{

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

}catch(UnsupportedEncodingException e) {

e.printStackTrace();

}

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

returnstr;

}

private staticString decodeHexTest(String str){

Hex hex =newHex();

try{

str =newString((byte[])hex.decode(str));

}catch(DecoderException e) {

e.printStackTrace();

}

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

returnstr;

}

3、 MD5加密

private staticString MD5Test(String str){

try{

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

}catch(UnsupportedEncodingException e) {

e.printStackTrace();

}

returnstr;

}

4、 SHA编码

private staticString ShaTest(String str){

try{

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

}catch(UnsupportedEncodingException e) {

e.printStackTrace();

}

returnstr;

}

5、 Metaphone和Soundex

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

http://350129923./blog/static/1795911363144659125/

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

import mons.codec.language.*;

import mons.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”);

}

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。