commons經常使用工具包的使用

===========commons-lang包======

   這個包中的不少工具類能夠簡化咱們的操做,在這裏簡單的研究其中的幾個工具類的使用。html

1.StringUtils工具類

  能夠判斷是不是空串,是否爲null,默認值設置等操做:java

    /**
     * StringUtils
     */
    public static void test1() {
        System.out.println(StringUtils.isBlank("   "));// true----能夠驗證null, ""," "等
        System.out.println(StringUtils.isBlank("null"));// false
        System.out.println(StringUtils.isAllLowerCase("null"));// t
        System.out.println(StringUtils.isAllUpperCase("XXXXXX"));// t
        System.out.println(StringUtils.isEmpty(" "));// f---爲null或者""返回true
        System.out.println(StringUtils.defaultIfEmpty(null, "default"));// 第二個參數是第一個爲null或者""的時候的取值
        System.out.println(StringUtils.defaultIfBlank("    ", "default"));//// 第二個參數是第一個爲null或者""或者"   "的時候的取值
    }

isBlank()  能夠驗證空格、null、"",若是是好幾個空格也返回truegit

isEmpty驗證不了空格,只有值爲null和""返回true spring

二者都驗證不了"null"字符串,因此若是驗證"null"還須要本身用equals進行驗證。sql

結果:apache

true
false
true
true
false
default
defaultjson

 

簡單的貼出幾個源碼便於記錄:api

    public static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (Character.isWhitespace(cs.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }

    public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }
    public static String defaultIfEmpty(String str, String defaultStr) {
        return StringUtils.isEmpty(str) ? defaultStr : str;
    }

 

  CharSequence是一個接口,String,StringBuffer,StringBuilder等都實現了此接口數組

public abstract interface CharSequence {
    public abstract int length();

    public abstract char charAt(int paramInt);

    public abstract CharSequence subSequence(int paramInt1, int paramInt2);

    public abstract String toString();
}

 

補充:StringUtils也能夠將集合和數組轉爲String,而且以指定符號連接裏面的數據app

        List list = new ArrayList(2);
        list.add("張三");
        list.add("李四");
        list.add("王五");
        String list2str = StringUtils.join(list, ",");
        System.out.println(list2str);

結果:

  張三,李四,王五

 

有時候咱們但願給拼接後的字符串都加上單引號,這個在拼接SQL  in條件的時候很是有用,例如:

        //需求:將逗號裏面的內容都加上單引號
        String string = "111,222,333";
        string = "'"+string+"'";//字符串先後加'
        string = StringUtils.join(string.split(","),"','");//先按逗號分隔爲數組,而後用','鏈接數組
        System.out.println(string);

結果:

'111','222','333'

 

  join方法也能夠接收數組,可變參數等,也能夠對數組進行拼接,以下:

        int[] numbers = { 1, 3, 5 };
        System.out.println(StringUtils.join(numbers, ','));

結果:

1,3,5

其重載方法以下:

 

補充:null和字符串"null"的區別

null在JVM中沒有分配內存,引用中無任何東西,debug也看不到任何東西,"null"字符串是一個正常的字符串,在JVM分配內存並且能夠看到東西

"null"字符串有東西

 

null無任何東西:

 

補充:String.format(format,Object)也能夠對字符串進行格式化,例如在數字前面補齊數字

        int num = 50;
        String format = String.format("%0" + 5 + "d", num);
        System.out.println(format);

結果:

00050

 

補充:StringUtils也能夠截取字符串,判斷是否大小寫等操做

        String string = "123_45_43_ss";
        System.out.println(StringUtils.isAllLowerCase(string));// 判斷所有小寫
        System.out.println(StringUtils.isAllUpperCase(string));// 判斷所有大寫
        System.out.println(StringUtils.substringAfter(string, "123"));// 截取123以後的
        System.out.println(StringUtils.substringBefore(string, "45"));// 截取45以前的
        System.out.println(StringUtils.substringBefore(string, "_"));// 截取第一個_以前的
        System.out.println(StringUtils.substringBeforeLast(string, "_"));// 截取最後一個_以前的
        System.out.println(StringUtils.substringAfter(string, "_"));// 截取第一個_以後的
        System.out.println(StringUtils.substringAfterLast(string, "_"));// 截取最後一個_以後的
        System.out.println(StringUtils.substringBetween("1234565432123456", "2", "6"));// 截取兩個之間的(都找的是第一個)

結果:

false
false
_45_43_ss
123_
123
123_45_43
45_43_ss
ss
345

 

補充:StringUtils也能夠將字符串分割爲數組

package cn.xm.exam.test;

import org.apache.commons.lang.StringUtils;

public class test {

    public static void main(String[] args) {
        String t = "tttt";
        System.out.println(StringUtils.split(t, ","));
    }
}

結果:

[Ljava.lang.String;@5a24389c

看過深刻理解JVM的都知道上面的[表明是一維數組類型,L表明是引用類型,後面的是String類型

 

補充:  isNoneBlank能夠支持多個參數,甚至String數組,用來判斷數組裏的每個字符串都是isNotBlank的。

 補充:StringUtils能夠獲取指定字符出現的次數

StringUtils.countMatches(str, ":")

 

 補充:StringUtils能夠第N次某字符串出現的位置

StringUtils.ordinalIndexOf(str, ":", 2)

 

補充:StringUtils能夠獲取指定字符串之間的字符串,並自動截取爲字符串數組

String[] substringBetweens = StringUtils.substringsBetween(str, ":", ":");

 

補充:StringUtils能夠獲取指定字符串之間的字符串(只取知足條件的前兩個)

StringUtils.substringBetween(str2, "/")

 

補充:Stringutils能夠左截取和右截取

        // 左右截取
        System.out.println(StringUtils.left("abc", 2));
        System.out.println(StringUtils.right("abc", 2));

結果:

ab
bc

查看源碼:

    public static String left(String str, int len) {
        if (str == null) {
            return null;
        }
        if (len < 0) {
            return EMPTY;
        }
        if (str.length() <= len) {
            return str;
        }
        return str.substring(0, len);
    }

    public static String right(String str, int len) {
        if (str == null) {
            return null;
        }
        if (len < 0) {
            return EMPTY;
        }
        if (str.length() <= len) {
            return str;
        }
        return str.substring(str.length() - len);
    }

 

補充:StringUtils能夠左右填充指定字符串

        // 左添加(默認添加空格)
        String leftPad = StringUtils.leftPad("2", 2);
        System.out.println(leftPad);
        String leftPad2 = StringUtils.leftPad("12", 3, "0");
        System.out.println(leftPad2);

        // 右添加(默認添加空格)
        String rightPad = StringUtils.rightPad("2", 2);
        System.out.println(rightPad);
        String rightPad2 = StringUtils.rightPad("12", 3, "0");
        System.out.println(rightPad2);

結果:

2
012
2
120

 補充:StringUtils能夠忽略大小寫判斷equals以及contains等

import org.apache.commons.lang3.StringUtils;

public class Plaintest {

    public static void main(String[] args) {
        boolean equalsIgnoreCase = StringUtils.equalsIgnoreCase("AA", "aa");
        System.out.println(equalsIgnoreCase);

        boolean containsIgnoreCase = StringUtils.containsIgnoreCase("Abc", "BC");
        System.out.println(containsIgnoreCase);
    }
}

結果:

true
true

 

2.StringEscapeUtils----------轉義字符串的工具類

    /**
     * StringEscapeUtils
     */
    public static  void test2(){
        //1.防止sql注入------原理是將'替換爲''
        System.out.println(org.apache.commons.lang.StringEscapeUtils.escapeSql("sss"));
        //2.轉義/反轉義html
        System.out.println( org.apache.commons.lang.StringEscapeUtils.escapeHtml("<a>dddd</a>"));   //&lt;a&gt;dddd&lt;/a&gt;
        System.out.println(org.apache.commons.lang.StringEscapeUtils.unescapeHtml("&lt;a&gt;dddd&lt;/a&gt;"));  //<a>dddd</a>
        //3.轉義/反轉義JS
        System.out.println(org.apache.commons.lang.StringEscapeUtils.escapeJavaScript("<script>alert('1111')</script>"));   
        //4.把字符串轉爲unicode編碼
        System.out.println(org.apache.commons.lang.StringEscapeUtils.escapeJava("中國"));   
        System.out.println(org.apache.commons.lang.StringEscapeUtils.unescapeJava("\u4E2D\u56FD"));  
        //5.轉義JSON
        System.out.println(org.apache.commons.lang3.StringEscapeUtils.escapeJson("{name:'qlq'}"));   
    }

 

3.NumberUtils--------字符串轉數據或者判斷字符串是不是數字經常使用工具類

    /**
     * NumberUtils
     */
    public static  void test3(){
        System.out.println(NumberUtils.isNumber("231232.8"));//true---判斷是不是數字
        System.out.println(NumberUtils.isDigits("2312332.5"));//false,判斷是不是整數
        System.out.println(NumberUtils.toDouble(null));//若是傳的值不正確返回一個默認值,字符串轉double,傳的不正確會返回默認值
        System.out.println(NumberUtils.createBigDecimal("333333"));//字符串轉bigdecimal
    }

 

4.BooleanUtils------------判斷Boolean類型工具類

    /**
     * BooleanUtils
     */
    public static  void test4(){
        System.out.println(BooleanUtils.isFalse(true));//false
        System.out.println(BooleanUtils.toBoolean("yes"));//true
        System.out.println(BooleanUtils.toBooleanObject(0));//false
        System.out.println(BooleanUtils.toStringYesNo(false));//no
        System.out.println(BooleanUtils.toBooleanObject("ok", "ok", "error", "null"));//true-----第一個參數是須要驗證的字符串,第二個是返回true的值,第三個是返回false的值,第四個是返回null的值
    }

 

5.SystemUtils----獲取系統信息(原理都是調用System.getProperty())

    /**
     * SystemUtils
     */
    public static  void test5(){
        System.out.println(SystemUtils.getJavaHome());
        System.out.println(SystemUtils.getJavaIoTmpDir());
        System.out.println(SystemUtils.getUserDir());
        System.out.println(SystemUtils.getUserHome());
        System.out.println(SystemUtils.JAVA_VERSION);
        System.out.println(SystemUtils.OS_NAME);
        System.out.println(SystemUtils.USER_TIMEZONE);
    }

 

6.DateUtils和DateFormatUtils能夠實現字符串轉date與date轉字符串,date比較前後問題

  DateUtils也能夠判斷是不是同一天等操做。

package zd.dms.test;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

public class PlainTest {
    public static void main(String[] args) {
        // DateFormatUtils----date轉字符串
        Date date = new Date();
        System.out.println(DateFormatUtils.format(date, "yyyy-MM-dd hh:mm:ss"));// 小寫的是12小時制
        System.out.println(DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));// 大寫的HH是24小時制

        // DateUtils ---加減指定的天數(也能夠加減秒、小時等操做)
        Date addDays = DateUtils.addDays(date, 2);
        System.out.println(DateFormatUtils.format(addDays, "yyyy-MM-dd HH:mm:ss"));
        Date addDays2 = DateUtils.addDays(date, -2);
        System.out.println(DateFormatUtils.format(addDays2, "yyyy-MM-dd HH:mm:ss"));

        // 原生日期判斷日期前後順序
        System.out.println(addDays2.after(addDays));
        System.out.println(addDays2.before(addDays));

        // DateUtils---字符串轉date
        String strDate = "2018-11-01 19:23:44";
        try {
            Date parseDateStrictly = DateUtils.parseDateStrictly(strDate, "yyyy-MM-dd HH:mm:ss");
            Date parseDate = DateUtils.parseDate(strDate, "yyyy-MM-dd HH:mm:ss");
            System.out.println(parseDateStrictly);
            System.out.println(parseDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

結果:

2018-11-02 07:53:50
2018-11-02 19:53:50
2018-11-04 19:53:50
2018-10-31 19:53:50
false
true
Thu Nov 01 19:23:44 CST 2018
Thu Nov 01 19:23:44 CST 2018

 

7.StopWatch提供秒錶的計時,暫停等功能

package cn.xm.exam.test;

import org.apache.commons.lang.time.StopWatch;

public class test implements AInterface, BInterface {
    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        stopWatch.stop();
        System.out.println(stopWatch.getStartTime());// 獲取開始時間
        System.out.println(stopWatch.getTime());// 獲取總的執行時間--單位是毫秒
    }
}

 結果:

1541754863180
5001

 

8.以Range結尾的類主要提供一些範圍的操做,包括判斷某些字符,數字等是否在這個範圍之內

        IntRange intRange = new IntRange(1, 5);
        System.out.println(intRange.getMaximumInteger());
        System.out.println(intRange.getMinimumInteger());
        System.out.println(intRange.containsInteger(6));
        System.out.println(intRange.containsDouble(3));

結果:

5
1
false
true

 

9.ArrayUtils操做數組,功能強大,能夠合併,判斷是否包含等操做

package cn.xm.exam.test;

import org.apache.commons.lang.ArrayUtils;

public class test implements AInterface, BInterface {
    public static void main(String[] args) {
        int array[] = { 1, 5, 5, 7 };
        System.out.println(array);

        // 增長元素
        array = ArrayUtils.add(array, 9);
        System.out.println(ArrayUtils.toString(array));

        // 刪除元素
        array = ArrayUtils.remove(array, 3);
        System.out.println(ArrayUtils.toString(array));

        // 反轉數組
        ArrayUtils.reverse(array);
        System.out.println(ArrayUtils.toString(array));

        // 查詢數組索引
        System.out.println(ArrayUtils.indexOf(array, 5));

        // 判斷數組中是否包含指定值
        System.out.println(ArrayUtils.contains(array, 5));

        // 合併數組
        array = ArrayUtils.addAll(array, new int[] { 1, 5, 6 });
        System.out.println(ArrayUtils.toString(array));
    }
}

結果:

[I@3cf5b814
{1,5,5,7,9}
{1,5,5,9}
{9,5,5,1}
1
true
{9,5,5,1,1,5,6}

 

補充:ArrayUtils能夠將包裝類型的數組轉變爲基本類型的數組。

package cn.xm.exam.test;

import org.apache.commons.lang.ArrayUtils;

public class test {
    public static void main(String[] args) {
        Integer integer[] = new Integer[] { 0, 1, 2 };
        System.out.println(integer.getClass());

        int[] primitive = ArrayUtils.toPrimitive(integer);
        System.out.println(primitive.getClass());
    }
}

結果:

class [Ljava.lang.Integer;
class [I

看過JVM的知道上面第一個表明是包裝類型一維數組,並且是Integer包裝類。L表明引用類型,[表明一維。

          第二個表明是基本數據類型int類型的一維數組。

 

補充:ArrayUtils也能夠判斷數組是否爲null或者數組大小是否爲0

    /**
     * <p>Checks if an array of Objects is empty or <code>null</code>.</p>
     *
     * @param array  the array to test
     * @return <code>true</code> if the array is empty or <code>null</code>
     * @since 2.1
     */
    public static boolean isEmpty(Object[] array) {
        return array == null || array.length == 0;
    }

 

ArrayUtils結合java.lang.reflect.Array工具類,能夠知足數組的基本操做,Array的方法以下:

 補充:ArrayUtils.remove()是根據下標移除,也能夠移除元素:從該數組中刪除第一次出現的指定元素,返回一個新的數組。

        int array[] = { 1, 5, 5, 7 };
        System.out.println(ArrayUtils.toString(array));

        // 刪除元素
        array = ArrayUtils.removeElement(array, 5);
        System.out.println(ArrayUtils.toString(array));

結果:

{1,5,5,7}
{1,5,7}

上面是刪除第一個出現的元素,若是須要刪除全部的,能夠用:

        int array[] = { 1, 5, 5, 7 };
        System.out.println(ArrayUtils.toString(array));

        // 刪除元素
        while (ArrayUtils.contains(array, 5)) {
            array = ArrayUtils.removeElement(array, 5);
        }
        System.out.println(ArrayUtils.toString(array));

結果:

{1,5,5,7}
{1,7}

 

8.  反射工具類的使用

一個普通的java:

package cn.xm.exam.test.p1;

public class Person {
    private String name;

    public static void staticMet(String t) {
        System.out.println(t);
    }

    public Person(String name) {
        this.name = name;
    }

    public String call(String string) {
        System.out.println(name);
        System.out.println(string);
        return string;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "test [name=" + name + "]";
    }
}

 

反射工具類操做:

package cn.xm.exam.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.lang.reflect.ConstructorUtils;
import org.apache.commons.lang.reflect.FieldUtils;
import org.apache.commons.lang.reflect.MethodUtils;

import cn.xm.exam.test.p1.Person;

public class test {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        // ConstructorUtils工具類的使用
        Constructor accessibleConstructor = ConstructorUtils.getAccessibleConstructor(Person.class, String.class);
        Person newInstance = (Person) accessibleConstructor.newInstance("test");
        System.out.println(newInstance.getClass());
        System.out.println(newInstance);

        // MethodUtils的使用
        Method accessibleMethod = MethodUtils.getAccessibleMethod(Person.class, "call", String.class);
        Object invoke = accessibleMethod.invoke(newInstance, "參數");
        System.out.println(invoke);
        // 調用靜態方法
        MethodUtils.invokeStaticMethod(Person.class, "staticMet", "靜態方法");

        // FieldUtils 暴力獲取私有變量(第三個參數表示是否強制獲取)---反射方法修改元素的值
        Field field = FieldUtils.getField(Person.class, "name", true);
        field.setAccessible(true);
        System.out.println(field.getType());
        field.set(newInstance, "修改後的值");
        System.out.println(newInstance.getName());
    }
}

結果:

class cn.xm.exam.test.p1.Person
test [name=test]
test
參數
參數
靜態方法
class java.lang.String
修改後的值

9.  EqualsBuilder 能夠用於拼接多個條件進行equals比較

例如:

        EqualsBuilder equalsBuilder = new EqualsBuilder();
        Integer integer1 = new Integer(1);
        Integer integer2 = new Integer(1);

        String string1 = "111";
        String string2 = "111";
        equalsBuilder.append(integer1, integer2);
        equalsBuilder.append(string1, string2);
        System.out.println(equalsBuilder.isEquals());

結果:

true

 查看源碼:(append的時候判斷兩個元素是否相等,若是equals已經等於false就直接返回)

    /**
     * <p>Test if two <code>Object</code>s are equal using their
     * <code>equals</code> method.</p>
     *
     * @param lhs  the left hand object
     * @param rhs  the right hand object
     * @return EqualsBuilder - used to chain calls.
     */
    public EqualsBuilder append(Object lhs, Object rhs) {
        if (isEquals == false) {
            return this;
        }
        if (lhs == rhs) {
            return this;
        }
        if (lhs == null || rhs == null) {
            this.setEquals(false);
            return this;
        }
        Class lhsClass = lhs.getClass();
        if (!lhsClass.isArray()) {
            // The simple case, not an array, just test the element
            isEquals = lhs.equals(rhs);
        } else if (lhs.getClass() != rhs.getClass()) {
            // Here when we compare different dimensions, for example: a boolean[][] to a boolean[] 
            this.setEquals(false);
        }
        // 'Switch' on type of array, to dispatch to the correct handler
        // This handles multi dimensional arrays of the same depth
        else if (lhs instanceof long[]) {
            append((long[]) lhs, (long[]) rhs);
        } else if (lhs instanceof int[]) {
            append((int[]) lhs, (int[]) rhs);
        } else if (lhs instanceof short[]) {
            append((short[]) lhs, (short[]) rhs);
        } else if (lhs instanceof char[]) {
            append((char[]) lhs, (char[]) rhs);
        } else if (lhs instanceof byte[]) {
            append((byte[]) lhs, (byte[]) rhs);
        } else if (lhs instanceof double[]) {
            append((double[]) lhs, (double[]) rhs);
        } else if (lhs instanceof float[]) {
            append((float[]) lhs, (float[]) rhs);
        } else if (lhs instanceof boolean[]) {
            append((boolean[]) lhs, (boolean[]) rhs);
        } else {
            // Not an array of primitives
            append((Object[]) lhs, (Object[]) rhs);
        }
        return this;
    }

補充:利用EqualsBuilder和HashCodeBuilder進行重寫equals方法和hasCode方法:

package cn.qlq;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class User implements Cloneable {

    private int age;
    private String name, sex;

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (obj == this) {
            return true;
        }

        if (!(obj instanceof User)) {
            return false;
        }

        final User tmpUser = (User) obj;
        return new EqualsBuilder().appendSuper(super.equals(obj)).append(name, tmpUser.getName()).isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(name).toHashCode();
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User [age=" + age + ", name=" + name + ", sex=" + sex + "]";
    }

}

 

10.  RandomStringUtils可用於生成隨機數和隨機字符串 

        // 第一個參數表示生成位數,第二個表示是否生成字母,第三個表示是否生成數字
        System.out.println(RandomStringUtils.random(15, true, false));

        // 長度、起始值、結束值、是否使用字母、是否生成數字
        System.out.println(RandomStringUtils.random(15, 5, 129, true, false));

        System.out.println(RandomStringUtils.random(22));

        // 從指定字符串隨機生成
        System.out.println(RandomStringUtils.random(15, "abcdefgABCDEFG123456789"));

        // 從字母中抽取
        System.out.println(RandomStringUtils.randomAlphabetic(15));

        // 從數字抽取
        System.out.println(RandomStringUtils.randomNumeric(15));

        // ASCII between 32 and 126 =內部調用(random(count, 32, 127, false,false);)
        System.out.println(RandomStringUtils.randomAscii(15));

結果:

JDibosuEOUepHtO
LXrzlRaANphURKS
ဧ큵䳵᩠K훸쟌ᚪ惥㈤ꃣ嚶爆䴄毟鰯韭;䡶ꑉ凷訩
5F5D919d77fEEA9
oTmXgAbiZWFUDRc
843164814767664
p(_xsQIp/&<Jc$Z

 

11.RandomUtils可用於生成必定範圍內整數、float、boolean等值。最新版的commons-lang包還能夠提供上限、下限

    public static void main(String[] args) {
        List<Object> result = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            result.add(RandomUtils.nextInt());
        }
        System.out.println(StringUtils.join(result, ","));

        result = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            result.add(RandomUtils.nextInt(20));
        }
        System.out.println(StringUtils.join(result, ","));

        result = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            result.add(org.apache.commons.lang3.RandomUtils.nextInt(0, 10));
        }
        System.out.println(StringUtils.join(result, ","));

        result = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            result.add(org.apache.commons.lang3.RandomUtils.nextLong(5L, 6L));
        }
        System.out.println(StringUtils.join(result, ","));

        result = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            result.add(org.apache.commons.lang3.RandomUtils.nextFloat(0.5F, 0.6F));
        }
        System.out.println(StringUtils.join(result, ","));
    }

結果:

391357754,492392032,492524087,666171631,473008086,2089602614,1303315335,494646254,1863562131,182849529,207273461,1857831948,1197203156,864149196,956426242,1263147526,2070274937,931371426,478106765,838690870,723564037,100543521,319440652,1438255942,1495754097,1537242017,1161118057,534187007,957222284,553366099
2,7,5,10,3,1,19,1,19,11,7,13,10,14,9,2,10,14,1,9,8,1,1,8,3,13,9,18,4,6
2,5,7,9,5,1,3,6,7,7,3,5,3,7,3,6,8,4,2,9,8,3,6,5,9,7,1,9,9,4
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5
0.52966917,0.52869964,0.58883214,0.53288007,0.5808929,0.56509304,0.5022589,0.53946894,0.5280939,0.5391899

 

========commons-collections包中的經常使用的工具類==

1. CollectionUtils工具類用於操做集合,  isEmpty () 方法最有用   (commons-collections包中的類)

package cn.xm.exam.test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

public class test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("str1");
        list.add("str2");

        List<String> list1 = new ArrayList<String>();
        list1.add("str1");
        list1.add("str21");

        // 判斷是否有任何一個相同的元素
        System.out.println(CollectionUtils.containsAny(list, list1));

        // 求並集(自動去重)
        List<String> list3 = (List<String>) CollectionUtils.union(list, list1);
        System.out.println(list3);

        // 求交集(兩個集合中都有的元素)
        Collection intersection = CollectionUtils.intersection(list, list1);
        System.out.println("intersection->" + intersection);

        // 求差集(並集去掉交集,也就是list中有list1中沒有,list1中有list中沒有)
        Collection intersection1 = CollectionUtils.disjunction(list, list1);
        System.out.println("intersection1->" + intersection1);

        // 獲取一個同步的集合
        Collection synchronizedCollection = CollectionUtils.synchronizedCollection(list);

        // 驗證集合是否爲null或者集合的大小是否爲0,同理有isNouEmpty方法
        List list4 = null;
        List list5 = new ArrayList<>();
        System.out.println(CollectionUtils.isEmpty(list4));
        System.out.println(CollectionUtils.isEmpty(list5));
    }
}

結果:

true
[str2, str21, str1]
intersection->[str1]
intersection1->[str2, str21]
true
true

 

補充:此工具類還能夠向集合中加數組元素

        List<String> list = new ArrayList<>();
        String s[] = { "1", "2" };
        CollectionUtils.addAll(list, s);
        list.add("3");
        System.out.println(list);

結果:

[1, 2, 3]

 

2.   MapUtils工具類,isEmpty最有用(commons-collections包中的類)

  能夠用於map判斷null和size爲0,也能夠直接獲取map中的值爲指定類型,沒有的返回null

package cn.xm.exam.test;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.NumberUtils;

import ognl.MapElementsAccessor;

public class test {
    public static void main(String[] args) {
        Map map = null;
        Map map2 = new HashMap();
        Map map3 = new HashMap<>();
        map3.put("xxx", "xxx");
        // 檢驗爲empty能夠驗證null和size爲0的狀況
        System.out.println(MapUtils.isEmpty(map));
        System.out.println(MapUtils.isEmpty(map2));
        System.out.println(MapUtils.isEmpty(map3));

        String string = MapUtils.getString(map3, "eee");
        String string2 = MapUtils.getString(map3, "xxx");
        Integer integer = MapUtils.getInteger(map3, "xxx");
        System.out.println("string->" + string);
        System.out.println("string2->" + string2);
        System.out.println("integer->" + integer);
        System.out.println(integer == null);
    }
}

結果:

true
true
false
INFO: Exception: java.text.ParseException: Unparseable number: "xxx"
string->null
string2->xxx
integer->null
true

 

 MapUtils.isEmpty根蹤源碼:

    public static boolean isEmpty(Map map) {
        return (map == null || map.isEmpty());
    }

 

map.isEmpty()代碼查看hashmap:
    public boolean isEmpty() {
        return size == 0;
    }

 

補充:MapUtils也能夠獲取值做爲String,獲取不到取默認值:

        //獲取字符串,若是獲取不到能夠返回一個默認值
        String string3 = MapUtils.getString(map3, "eee","沒有值");

 

 查看源碼:

    /**
     *  Looks up the given key in the given map, converting the result into
     *  a string, using the default value if the the conversion fails.
     *
     *  @param map  the map whose value to look up
     *  @param key  the key of the value to look up in that map
     *  @param defaultValue  what to return if the value is null or if the
     *     conversion fails
     *  @return  the value in the map as a string, or defaultValue if the 
     *    original value is null, the map is null or the string conversion
     *    fails
     */
    public static String getString( Map map, Object key, String defaultValue ) {
        String answer = getString( map, key );
        if ( answer == null ) {
            answer = defaultValue;
        }
        return answer;
    }

 

 

補充:網上總結的常見工具類的使用

一. org.apache.commons.io.IOUtils

closeQuietly:關閉一個IO流、socket、或者selector且不拋出異常,一般放在finally塊
toString:轉換IO流、 Uri、 byte[]爲String
copy:IO流數據複製,從輸入流寫到輸出流中,最大支持2GB
toByteArray:從輸入流、URI獲取byte[]
write:把字節. 字符等寫入輸出流
toInputStream:把字符轉換爲輸入流
readLines:從輸入流中讀取多行數據,返回List<String>
copyLarge:同copy,支持2GB以上數據的複製
lineIterator:從輸入流返回一個迭代器,根據參數要求讀取的數據量,所有讀取,若是數據不夠,則失敗

 

二. org.apache.commons.io.FileUtils

deleteDirectory:刪除文件夾
readFileToString:以字符形式讀取文件內容
deleteQueitly:刪除文件或文件夾且不會拋出異常
copyFile:複製文件
writeStringToFile:把字符寫到目標文件,若是文件不存在,則建立
forceMkdir:強制建立文件夾,若是該文件夾父級目錄不存在,則建立父級
write:把字符寫到指定文件中
listFiles:列舉某個目錄下的文件(根據過濾器)
copyDirectory:複製文件夾
forceDelete:強制刪除文件

 

三. org.apache.commons.lang.StringUtils

isBlank:字符串是否爲空 (trim後判斷)
isEmpty:字符串是否爲空 (不trim並判斷)
equals:字符串是否相等
join:合併數組爲單一字符串,可傳分隔符
split:分割字符串
EMPTY:返回空字符串
trimToNull:trim後爲空字符串則轉換爲null
replace:替換字符串

 

四. org.apache.http.util.EntityUtils

toString:把Entity轉換爲字符串
consume:確保Entity中的內容所有被消費。能夠看到源碼裏又一次消費了Entity的內容,假如用戶沒有消費,那調用Entity時候將會把它消費掉
toByteArray:把Entity轉換爲字節流
consumeQuietly:和consume同樣,但不拋異常
getContentCharset:獲取內容的編碼

 

五. org.apache.commons.lang3.StringUtils

isBlank:字符串是否爲空 (trim後判斷)
isEmpty:字符串是否爲空 (不trim並判斷)
equals:字符串是否相等
join:合併數組爲單一字符串,可傳分隔符
split:分割字符串
EMPTY:返回空字符串
replace:替換字符串
capitalize:首字符大寫

 

六. org.apache.commons.io.FilenameUtils

getExtension:返回文件後綴名
getBaseName:返回文件名,不包含後綴名
getName:返回文件全名
concat:按命令行風格組合文件路徑(詳見方法註釋)
removeExtension:刪除後綴名
normalize:使路徑正常化
wildcardMatch:匹配通配符
seperatorToUnix:路徑分隔符改爲unix系統格式的,即/
getFullPath:獲取文件路徑,不包括文件名
isExtension:檢查文件後綴名是否是傳入參數(List<String>)中的一個

 

七. org.springframework.util.StringUtils

hasText:檢查字符串中是否包含文本
hasLength:檢測字符串是否長度大於0
isEmpty:檢測字符串是否爲空(若傳入爲對象,則判斷對象是否爲null)
commaDelimitedStringToArray:逗號分隔的String轉換爲數組
collectionToDelimitedString:把集合轉爲CSV格式字符串
replace 替換字符串
delimitedListToStringArray:至關於split
uncapitalize:首字母小寫
collectionToDelimitedCommaString:把集合轉爲CSV格式字符串
tokenizeToStringArray:和split基本同樣,但能自動去掉空白的單詞

 

八. org.apache.commons.lang.ArrayUtils

contains:是否包含某字符串
addAll:添加整個數組
clone:克隆一個數組
isEmpty:是否空數組
add:向數組添加元素
subarray:截取數組
indexOf:查找某個元素的下標
isEquals:比較數組是否相等
toObject:基礎類型數據數組轉換爲對應的Object數組

 

九. org.apache.commons.lang.StringEscapeUtils

參考十五:
org.apache.commons.lang3.StringEscapeUtils


十. org.apache.http.client.utils.URLEncodedUtils

format:格式化參數,返回一個HTTP POST或者HTTP PUT可用application/x-www-form-urlencoded字符串
parse:把String或者URI等轉換爲List<NameValuePair>

 

十一. org.apache.commons.codec.digest.DigestUtils

md5Hex:MD5加密,返回32位字符串
sha1Hex:SHA-1加密
sha256Hex:SHA-256加密
sha512Hex:SHA-512加密
md5:MD5加密,返回16位字符串

 

十二. org.apache.commons.collections.CollectionUtils

isEmpty:是否爲空
select:根據條件篩選集合元素
transform:根據指定方法處理集合元素,相似List的map()
filter:過濾元素,雷瑟List的filter()
find:基本和select同樣
collect:和transform 差很少同樣,可是返回新數組
forAllDo:調用每一個元素的指定方法
isEqualCollection:判斷兩個集合是否一致

 

十三. org.apache.commons.lang3.ArrayUtils

contains:是否包含某個字符串
addAll:添加整個數組
clone:克隆一個數組
isEmpty:是否空數組
add:向數組添加元素
subarray:截取數組
indexOf:查找某個元素的下標
isEquals:比較數組是否相等
toObject:基礎類型數據數組轉換爲對應的Object數組

 

十四. org.apache.commons.beanutils.PropertyUtils

getProperty:獲取對象屬性值
setProperty:設置對象屬性值
getPropertyDiscriptor:獲取屬性描述器
isReadable:檢查屬性是否可訪問
copyProperties:複製屬性值,從一個對象到另外一個對象
getPropertyDiscriptors:獲取全部屬性描述器
isWriteable:檢查屬性是否可寫
getPropertyType:獲取對象屬性類型

 

十五. org.apache.commons.lang3.StringEscapeUtils

unescapeHtml4:轉義html
escapeHtml4:反轉義html
escapeXml:轉義xml
unescapeXml:反轉義xml
escapeJava:轉義unicode編碼
escapeEcmaScript:轉義EcmaScript字符
unescapeJava:反轉義unicode編碼
escapeJson:轉義json字符
escapeXml10:轉義Xml10
這個如今已經廢棄了,建議使用commons-text包裏面的方法。

 

十六. org.apache.commons.beanutils.BeanUtils

copyPeoperties:複製屬性值,從一個對象到另外一個對象
getProperty:獲取對象屬性值
setProperty:設置對象屬性值
populate:根據Map給屬性複製
copyPeoperty:複製單個值,從一個對象到另外一個對象
cloneBean:克隆bean實例

  如今你只要瞭解了以上16種最流行的工具類方法,你就沒必要要再本身寫工具類了,沒必要重複造輪子。大部分工具類方法經過其名字就能明白其用途,若是不清楚的,能夠看下別人是怎麼用的,或者去網上查詢其用法。  另外,工具類,根據阿里開發手冊,包名若是要使用util不能帶s,工具類命名爲 XxxUtils(參考spring命名)

相關文章
相關標籤/搜索