http://www.open-open.com/bbs/view/1318864045468
http://www.oschina.net/code/snippet_2765_14434
這一組API的所有包名都以org.apache.commons.lang開頭,共有如下8個包:
org.apache.commons.lang
org.apache.commons.lang.builder
org.apache.commons.lang.enum
org.apache.commons.lang.enums
org.apache.commons.lang.exception
org.apache.commons.lang.math
org.apache.commons.lang.mutable
org.apache.commons.lang.time
其中的lang.enum已不建議使用,替代它的是緊隨其後的lang.enums包。 lang包主要是一些可以高度重用的Util類;lang.builder包包含了一組用於產生每個Java類中都常使用到的toString()、 hashCode()、equals()、compareTo()等等方法的構造器;lang.enums包顧名思義用於處理枚 舉;lang.exception包用於處理Java標準API中的exception,為1.4之前版本提供Nested Exception功能;lang.math包用於處理數字;lang.mutable用於封裝值型變數;lang.time包提供處理日期和時間的功 能。
由於Commons的包和類實在很多,不可能一個一個講了,在接下來的專題文章中我就只分別過一下lang、lang.builder、lang.math和lang.time這幾個包和常見的用法,其他的我們可以在用到時臨時參考一下Javadoc。位置就在安裝路徑的
…\commons-lang-2.1\docs\api\index.html
我們首先來看org.apache.commons.lang包,這個包提供了一些有用的包含static方法的Util類。除了6個Exception類和2個已經deprecated的數字類之外,commons.lang包共包含了17個實用的類:
ArrayUtils – 用於對數組的操作,如添加、尋找、刪除、子數組、倒序、元素類型轉換等;
BitField – 用於操作位元,提供了一些方便而安全的方法;
BooleanUtils – 用於操作和轉換boolean或者Boolean及相應的數組;
CharEncoding – 包含了Java環境支援的字元編碼,提供是否支援某種編碼的判斷;
CharRange – 用於設定字元範圍並做相應檢查;
CharSet – 用於設定一組字元作為範圍並做相應檢查;
CharSetUtils – 用於操作CharSet;
CharUtils – 用於操作char值和Character對象;
ClassUtils – 用於對Java類的操作,不使用反射;
ObjectUtils – 用於操作Java對象,提供null安全的訪問和其他一些功能;
RandomStringUtils – 用於產生隨機的字串;
SerializationUtils – 用於處理對象序列化,提供比一般Java序列化更進階的處理能力;
StringEscapeUtils – 用於正確處理逸出字元,產生正確的Java、JavaScript、HTML、XML和SQL代碼;
StringUtils – 處理String的核心類,提供了相當多的功能;
SystemUtils – 在java.lang.System基礎上提供更方便的訪問,如使用者路徑、Java版本、時區、作業系統等判斷;
Validate – 提供驗證的操作,有點類似assert斷言;
WordUtils – 用於處理單詞大小寫、換行等。
public class TestLangDemo {public void charSetDemo() {System.out.println("**CharSetDemo**");CharSet charSet = CharSet.getInstance("aeiou");String demoStr = "The quick brown fox jumps over the lazy dog.";int count = 0;for (int i = 0, len = demoStr.length(); i < len; i++) {if (charSet.contains(demoStr.charAt(i))) {count++;}}System.out.println("count: " + count);}public void charSetUtilsDemo() {System.out.println("**CharSetUtilsDemo**");System.out.println("計算字串中包含某字元數.");System.out.println(CharSetUtils.count("The quick brown fox jumps over the lazy dog.", "aeiou"));System.out.println("刪除字串中某字元.");System.out.println(CharSetUtils.delete("The quick brown fox jumps over the lazy dog.", "aeiou"));System.out.println("保留字元串中某字元.");System.out.println(CharSetUtils.keep("The quick brown fox jumps over the lazy dog.", "aeiou"));System.out.println("合并重複的字元.");System.out.println(CharSetUtils.squeeze("a bbbbbb c dd", "b d"));}public void objectUtilsDemo() {System.out.println("**ObjectUtilsDemo**");System.out.println("Object為null時,預設列印某字元.");Object obj = null;System.out.println(ObjectUtils.defaultIfNull(obj, "空"));System.out.println("驗證兩個引用是否指向的Object是否相等,取決於Object的equals()方法.");Object a = new Object();Object b = a;Object c = new Object();System.out.println(ObjectUtils.equals(a, b));System.out.println(ObjectUtils.equals(a, c));System.out.println("用父類Object的toString()方法返回對象資訊.");Date date = new Date();System.out.println(ObjectUtils.identityToString(date));System.out.println(date);System.out.println("返回類本身的toString()方法結果,對象為null時,返回0長度字串.");System.out.println(ObjectUtils.toString(date));System.out.println(ObjectUtils.toString(null));System.out.println(date);}public void serializationUtilsDemo() {System.out.println("*SerializationUtils**");Date date = new Date();byte[] bytes = SerializationUtils.serialize(date);System.out.println(ArrayUtils.toString(bytes));System.out.println(date);Date reDate = (Date) SerializationUtils.deserialize(bytes);System.out.println(reDate);System.out.println(ObjectUtils.equals(date, reDate));System.out.println(date == reDate);FileOutputStream fos = null;FileInputStream fis = null;try {fos = new FileOutputStream(new File("d:/test.txt"));fis = new FileInputStream(new File("d:/test.txt"));SerializationUtils.serialize(date, fos);Date reDate2 = (Date) SerializationUtils.deserialize(fis);System.out.println(date.equals(reDate2));} catch (FileNotFoundException e) {e.printStackTrace();} finally {try {fos.close();fis.close();} catch (IOException e) {e.printStackTrace();}}}public void randomStringUtilsDemo() {System.out.println("**RandomStringUtilsDemo**");System.out.println("產生指定長度的隨機字串,好像沒什麼用.");System.out.println(RandomStringUtils.random(500));System.out.println("在指定字串中產生長度為n的隨機字串.");System.out.println(RandomStringUtils.random(5, "abcdefghijk"));System.out.println("指定從字元或數字中產生隨機字串.");System.out.println(RandomStringUtils.random(5, true, false));System.out.println(RandomStringUtils.random(5, false, true));}public void stringUtilsDemo() {System.out.println("**StringUtilsDemo**");System.out.println("將字串重複n次,將文字按某寬度置中,將字串數組用某字串串連.");String[] header = new String[3];header[0] = StringUtils.repeat("*", 50);header[1] = StringUtils.center(" StringUtilsDemo ", 50, "^O^");header[2] = header[0];String head = StringUtils.join(header, "\n");System.out.println(head);System.out.println("縮短到某長度,用...結尾.");System.out.println(StringUtils.abbreviate("The quick brown fox jumps over the lazy dog.", 10));System.out.println(StringUtils.abbreviate("The quick brown fox jumps over the lazy dog.", 15, 10));System.out.println("返回兩字串不同處索引號.");System.out.println(StringUtils.indexOfDifference("aaabc", "aaacc"));System.out.println("返回兩字串不同處開始至結束.");System.out.println(StringUtils.difference("aaabcde", "aaaccde"));System.out.println("截去字串為以指定字串結尾的部分.");System.out.println(StringUtils.chomp("aaabcde", "de"));System.out.println("檢查一字串是否為另一字串的子集.");System.out.println(StringUtils.containsOnly("aad", "aadd"));System.out.println("檢查一字串是否不是另一字串的子集.");System.out.println(StringUtils.containsNone("defg", "aadd"));System.out.println("檢查一字串是否包含另一字串.");System.out.println(StringUtils.contains("defg", "ef"));System.out.println(StringUtils.containsOnly("ef", "defg"));System.out.println("返回可以處理null的toString().");System.out.println(StringUtils.defaultString("aaaa"));System.out.println("?" + StringUtils.defaultString(null) + "!");System.out.println("去除字元中的空格.");System.out.println(StringUtils.deleteWhitespace("aa bb cc"));System.out.println("分隔字元處理成數組.");String[] strArray = StringUtils.split("a,b,,c,d,null,e", ",");System.out.println(strArray.length);System.out.println(strArray.toString());System.out.println("判斷是否是某類字元.");System.out.println(StringUtils.isAlpha("ab"));System.out.println(StringUtils.isAlphanumeric("12"));System.out.println(StringUtils.isBlank(""));System.out.println(StringUtils.isNumeric("123"));}public void systemUtilsDemo() {System.out.println(genHeader("SystemUtilsDemo"));System.out.println("獲得系統檔案分隔字元.");System.out.println(SystemUtils.FILE_SEPARATOR);System.out.println("獲得源檔案編碼.");System.out.println(SystemUtils.FILE_ENCODING);System.out.println("獲得ext目錄.");System.out.println(SystemUtils.JAVA_EXT_DIRS);System.out.println("獲得java版本.");System.out.println(SystemUtils.JAVA_VM_VERSION);System.out.println("獲得java廠商.");System.out.println(SystemUtils.JAVA_VENDOR);}public void classUtilsDemo() {System.out.println(genHeader("ClassUtilsDemo"));System.out.println("擷取類實現的所有介面.");System.out.println(ClassUtils.getAllInterfaces(Date.class));System.out.println("擷取類所有父類.");System.out.println(ClassUtils.getAllSuperclasses(Date.class));System.out.println("擷取簡單類名.");System.out.println(ClassUtils.getShortClassName(Date.class));System.out.println("擷取包名.");System.out.println(ClassUtils.getPackageName(Date.class));System.out.println("判斷是否可以轉型.");System.out.println(ClassUtils.isAssignable(Date.class, Object.class));System.out.println(ClassUtils.isAssignable(Object.class, Date.class));}public void stringEscapeUtilsDemo() {System.out.println(genHeader("StringEcsapeUtils"));System.out.println("轉換特殊字元.");System.out.println("html:" + StringEscapeUtils.escapeHtml3(" "));System.out.println("html:" + StringEscapeUtils.escapeHtml4(" "));System.out.println("html:" + StringEscapeUtils.unescapeHtml3("<p>"));System.out.println("html:" + StringEscapeUtils.unescapeHtml4("<p>"));}private final class BuildDemo {String name;int age;public BuildDemo(String name, int age) {this.name = name;this.age = age;}public String toString() {ToStringBuilder tsb = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE);tsb.append("Name", name);tsb.append("Age", age);return tsb.toString();}public int hashCode() {HashCodeBuilder hcb = new HashCodeBuilder();hcb.append(name);hcb.append(age);return hcb.hashCode();}public boolean equals(Object obj) {if (!(obj instanceof BuildDemo)) {return false;}BuildDemo bd = (BuildDemo) obj;EqualsBuilder eb = new EqualsBuilder();eb.append(name, bd.name);eb.append(age, bd.age);return eb.isEquals();}}public void builderDemo() {System.out.println(genHeader("BuilderDemo"));BuildDemo obj1 = new BuildDemo("a", 1);BuildDemo obj2 = new BuildDemo("b", 2);BuildDemo obj3 = new BuildDemo("a", 1);System.out.println("toString()");System.out.println(obj1);System.out.println(obj2);System.out.println(obj3);System.out.println("hashCode()");System.out.println(obj1.hashCode());System.out.println(obj2.hashCode());System.out.println(obj3.hashCode());System.out.println("equals()");System.out.println(obj1.equals(obj2));System.out.println(obj1.equals(obj3));}public void numberUtils() {System.out.println(genHeader("NumberUtils"));System.out.println("字串轉為數字(不知道有什麼用).");System.out.println(NumberUtils.toInt("ba", 33));System.out.println("從數組中選出最大值.");System.out.println(NumberUtils.max(new int[] { 1, 2, 3, 4 }));System.out.println("判斷字串是否全是整數.");System.out.println(NumberUtils.isDigits("123.1"));System.out.println("判斷字串是否是有效數字.");System.out.println(NumberUtils.isNumber("0123.1"));}public void dateFormatUtilsDemo() {System.out.println(genHeader("DateFormatUtilsDemo"));System.out.println("格式化日期輸出.");System.out.println(DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));System.out.println("秒錶.");StopWatch sw = new StopWatch();sw.start();for (Iterator iterator = DateUtils.iterator(new Date(), DateUtils.RANGE_WEEK_CENTER); iterator.hasNext();) {Calendar cal = (Calendar) iterator.next();System.out.println(DateFormatUtils.format(cal.getTime(), "yy-MM-dd HH:mm"));}sw.stop();System.out.println("秒錶計時:" + sw.getTime());}private String genHeader(String head) {String[] header = new String[3];header[0] = StringUtils.repeat("*", 50);header[1] = StringUtils.center(" " + head + " ", 50, "^O^");header[2] = header[0];return StringUtils.join(header, "\n");}private void validateDemo() {String[] strarray = { "a", "b", "c" };System.out.println("驗證功能");System.out.println(Validate.notEmpty(strarray));}private void wordUtilsDemo() {System.out.println("單詞處理功能");String str1 = "wOrD";String str2 = "ghj\nui\tpo";System.out.println(WordUtils.capitalize(str1)); // 首字母大寫System.out.println(WordUtils.capitalizeFully(str1)); // 首字母大寫其它字母小寫char[] ctrg = { '.' };System.out.println(WordUtils.capitalizeFully("i aM.fine", ctrg)); // 在規則地方轉換System.out.println(WordUtils.initials(str1)); // 擷取首字母System.out.println(WordUtils.initials("Ben John Lee", null)); // 取每個單詞的首字母char[] ctr = { ' ', '.' };System.out.println(WordUtils.initials("Ben J.Lee", ctr)); // 按指定規則擷取首字母System.out.println(WordUtils.swapCase(str1)); // 大小寫逆轉System.out.println(WordUtils.wrap(str2, 1)); // 解析\n和\t等字元}/** * @param args */public static void main(String[] args) {TestLangDemo langDemo = new TestLangDemo();langDemo.charSetDemo();langDemo.charSetUtilsDemo();langDemo.objectUtilsDemo();langDemo.serializationUtilsDemo();langDemo.randomStringUtilsDemo();langDemo.stringUtilsDemo();langDemo.systemUtilsDemo();langDemo.classUtilsDemo();langDemo.stringEscapeUtilsDemo();langDemo.builderDemo();langDemo.numberUtils();langDemo.dateFormatUtilsDemo();langDemo.validateDemo();langDemo.wordUtilsDemo();}}