Apache Commons-Lang 簡介

一、前言

    Java碼農不識Apache,敲盡一生也枉然。旗下的開源項目衆多,各個都是吊炸天。今日且說Commons,輕輕點擊此鏈接進入Apache Commons主頁,Logging、Pool、Net、ONGL、EL、IO、DBCP、Email、Collection、Lang……等等項目中常用到的包。而這篇文章的主角Lang則是我們最常用的工具作爲jdk的補充,怎能不去詳細探究一番!


    下載地址:http://commons.apache.org/proper/commons-lang/download_lang.cgi


二、字符串的處理類(StringUtils)

    org.apache.commons.lang3.StringUtils 繼承Object,Operations on String that are null safe。所謂的null safe就是對String進行操作不會出現NullPointerException異常,很實用有沒有!以後再也不怕到處出現空指針異常了。先看看官方文檔中這個類都有些什麼方法:

wKiom1QWyv7wXBz4AAU5PodFOcs211.jpg

    這些方法基本上看方法名,就能猜出它大概的作用了。

//縮短到某長度,用...結尾.其實就是(substring(str, 0, max-3) + "...")
        //public static String abbreviate(String str,int maxWidth)
        StringUtils.abbreviate("abcdefg", 6);// ---"abc..."
        
        //字符串結尾的後綴是否與你要結尾的後綴匹配,若不匹配則添加後綴
        StringUtils.appendIfMissing("abc","xyz");//---"abcxyz"
        StringUtils.appendIfMissingIgnoreCase("abcXYZ","xyz");//---"abcXYZ"
        
        //首字母大小寫轉換
        StringUtils.capitalize("cat");//---"Cat"
        StringUtils.uncapitalize("Cat");//---"cat"
        
        //字符串擴充至指定大小且居中(若擴充大小少於原字符大小則返回原字符,若擴充大小爲 負數則爲0計算 )
        StringUtils.center("abcd", 2);//--- "abcd"
        StringUtils.center("ab", -1);//--- "ab"
        StringUtils.center("ab", 4);//---" ab "
        StringUtils.center("a", 4, "yz");//---"yayz"
        StringUtils.center("abc", 7, "");//---"  abc  "
        
        //去除字符串中的"\n", "\r", or "\r\n"
        StringUtils.chomp("abc\r\n");//---"abc"
        
        //判斷一字符串是否包含另一字符串
        StringUtils.contains("abc", "z");//---false
        StringUtils.containsIgnoreCase("abc", "A");//---true
        
        //統計一字符串在另一字符串中出現次數
        StringUtils.countMatches("abba", "a");//---2
        
        //刪除字符串中的梭有空格
        StringUtils.deleteWhitespace("   ab  c  ");//---"abc"
        
        //比較兩字符串,返回不同之處。確切的說是返回第二個參數中與第一個參數所不同的字符串
        StringUtils.difference("abcde", "abxyz");//---"xyz"
        
        //檢查字符串結尾後綴是否匹配
        StringUtils.endsWith("abcdef", "def");//---true
        StringUtils.endsWithIgnoreCase("ABCDEF", "def");//---true
        StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"});//---true
        
        //檢查起始字符串是否匹配
        StringUtils.startsWith("abcdef", "abc");//---true
        StringUtils.startsWithIgnoreCase("ABCDEF", "abc");//---true
        StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"});//---true
        
        //判斷兩字符串是否相同
        StringUtils.equals("abc", "abc");//---true
        StringUtils.equalsIgnoreCase("abc", "ABC");//---true
        
        //比較字符串數組內的所有元素的字符序列,起始一致則返回一致的字符串,若無則返回""
        StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"});//---"ab"
        
        //正向查找字符在字符串中第一次出現的位置
        StringUtils.indexOf("aabaabaa", "b");//---2
        StringUtils.indexOf("aabaabaa", "b", 3);//---5(從角標3後查找)
        StringUtils.ordinalIndexOf("aabaabaa", "a", 3);//---1(查找第n次出現的位置)
        
        //反向查找字符串第一次出現的位置
        StringUtils.lastIndexOf("aabaabaa", 'b');//---5
        StringUtils.lastIndexOf("aabaabaa", 'b', 4);//---2
        StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2);//---1
        
        //判斷字符串大寫、小寫
        StringUtils.isAllUpperCase("ABC");//---true
        StringUtils.isAllLowerCase("abC");//---false
        
        //判斷是否爲空(注:isBlank與isEmpty 區別)
        StringUtils.isBlank(null);StringUtils.isBlank("");StringUtils.isBlank(" ");//---true
        StringUtils.isNoneBlank(" ", "bar");//---false
        
        StringUtils.isEmpty(null);StringUtils.isEmpty("");//---true
        StringUtils.isEmpty(" ");//---false
        StringUtils.isNoneEmpty(" ", "bar");//---true
        
        //判斷字符串數字
        StringUtils.isNumeric("123");//---false
        StringUtils.isNumeric("12 3");//---false (不識別運算符號、小數點、空格……)
        StringUtils.isNumericSpace("12 3");//---true
        
        //數組中加入分隔符號
        //StringUtils.join([1, 2, 3], ';');//---"1;2;3"
        
        //大小寫轉換
        StringUtils.upperCase("aBc");//---"ABC"
        StringUtils.lowerCase("aBc");//---"abc"
        StringUtils.swapCase("The dog has a BONE");//---"tHE DOG HAS A bone"
        
        //替換字符串內容……(replacePattern、replceOnce)
        StringUtils.replace("aba", "a", "z");//---"zbz"
        StringUtils.overlay("abcdef", "zz", 2, 4);//---"abzzef"(指定區域)
        StringUtils.replaceEach("abcde", new String[]{"ab", "d"},
                new String[]{"w", "t"});//---"wcte"(多組指定替換ab->w,d->t)
        
        //重複字符
        StringUtils.repeat('e', 3);//---"eee"
        
        //反轉字符串
        StringUtils.reverse("bat");//---"tab"
        
        //刪除某字符
        StringUtils.remove("queued", 'u');//---"qeed"
        
        //分割字符串
        StringUtils.split("a..b.c", '.');//---["a", "b", "c"]
        StringUtils.split("ab:cd:ef", ":", 2);//---["ab", "cd:ef"]
        StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2);//---["ab", "cd-!-ef"]
        StringUtils.splitByWholeSeparatorPreserveAllTokens("ab::cd:ef", ":");//-["ab"," ","cd","ef"]
        
        //去除首尾空格,類似trim……(stripStart、stripEnd、stripAll、stripAccents)
        StringUtils.strip(" ab c ");//---"ab c"
        StringUtils.stripToNull(null);//---null
        StringUtils.stripToEmpty(null);//---""
        
        //截取字符串
        StringUtils.substring("abcd", 2);//---"cd"
        StringUtils.substring("abcdef", 2, 4);//---"cd"
        
        //left、right從左(右)開始截取n位字符
        StringUtils.left("abc", 2);//---"ab"
        StringUtils.right("abc", 2);//---"bc"
        //從第n位開始截取m位字符       n  m
        StringUtils.mid("abcdefg", 2, 4);//---"cdef"
        
        StringUtils.substringBefore("abcba", "b");//---"a"
        StringUtils.substringBeforeLast("abcba", "b");//---"abc"
        StringUtils.substringAfter("abcba", "b");//---"cba"
        StringUtils.substringAfterLast("abcba", "b");//---"a"
        
        StringUtils.substringBetween("tagabctag", "tag");//---"abc"
        StringUtils.substringBetween("yabczyabcz", "y", "z");//---"abc"


三、其它類簡介

    RandomStringUtils:

        //隨機生成n位數數字
        RandomStringUtils.randomNumeric(n);
        //在指定字符串中生成長度爲n的隨機字符串
        RandomStringUtils.random(n, "abcdefghijk");
        //指定從字符或數字中生成隨機字符串
        System.out.println(RandomStringUtils.random(n, true, false));  
        System.out.println(RandomStringUtils.random(n, false, true));

    NumberUtils:

        //從數組中選出最大值
        NumberUtils.max(new int[] { 1, 2, 3, 4 });//---4
        //判斷字符串是否全是整數
        NumberUtils.isDigits("153.4");//--false
        //判斷字符串是否是有效數字
        NumberUtils.isNumber("0321.1");//---false   

    ArrayUtils:

        //創建數組
        String[] array = ArrayUtils.toArray("1", "2");
        //判斷兩個數據是否相等,如果內容相同, 順序相同 則返回 true
        ArrayUtils.isEquals(arr1,arr2);
        //判斷數組中是否包含某一對象
        ArrayUtils.contains(arr, "33");
        //二維數組轉換成MAP
        Map map = ArrayUtils.toMap(new String[][] { 
                { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } });

    DateUtils:

        //日期加n天
        DateUtils.addDays(new Date(), n);
        //判斷是否同一天
        DateUtils.isSameDay(date1, date2);
        //字符串時間轉換爲Date
        DateUtils.parseDate(str, parsePatterns);


四、結語

    本文只是簡單的介紹了commons-lang中的一些常用工具類,還有許多挺實用的就不一一列舉。還是要自己去查閱文檔試用了才能體會到它的簡便。


    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章