commons常用工具包的使用
===========commons-lang包======
這個包中的很多工具類可以簡化我們的操作,在這里簡單的研究其中的幾個工具類的使用。
1.StringUtils工具類
可以判斷是否是空串,是否為null,默認值設置等操作:
/** * 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、"",如果是好幾個空格也返回true
isEmpty驗證不了空格,只有值為null和""返回true
兩者都驗證不了"null"字符串,所以如果驗證"null"還需要自己用equals進行驗證。
結果:
true
false
true
true
false
default
default
簡單的貼出幾個源碼便於記錄:
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,並且以指定符號鏈接里面的數據
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----------轉義字符串的工具類
//1.防止sql注入------原理是將'替換為'' System.out.println(org.apache.commons.lang.StringEscapeUtils.escapeSql("1' or '1' = '1")); //2.轉義/反轉義html System.out.println( org.apache.commons.lang.StringEscapeUtils.escapeHtml("<a>dddd</a>")); //<a>dddd</a> System.out.println(org.apache.commons.lang.StringEscapeUtils.unescapeHtml("<a>dddd</a>")); //<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'}"));
結果:
1'' or ''1'' = ''1
<a>dddd</a>
<a>dddd</a>
<script>alert(\'1111\')<\/script>
\u4E2D\u56FD
中國
{name:'qlq'}
補充:關於SQL注入做進一步解釋。上面的防止SQL注入一般是對傳入的條件進行轉義,不可以對整條SQL進行轉義,整條轉義SQL執行的時候會報錯。防止惡意SQL。例如:
萬能用戶名和密碼如下:
String username = "1' or '1' = '1"; String password = "admin' or '1' = '1";
分別做轉義和不做轉義的情況如下:
String sql = "select * from user where username = '" + username + "' and password = '" + password + "'"; System.out.println(sql); String sql2 = "select * from user where username = '" + StringEscapeUtils.escapeSql(username) + "' and password = '" + StringEscapeUtils.escapeSql(password) + "'"; System.out.println(sql2);
結果:(轉義之后可以防止SQL注入,是將' 替換為 '' (一個單引號替換為兩個連着的單引號。將''識別為普通的字符串而不是結束符,也就是轉義后的username和password整體作為參數))
select * from user where username = '1' or '1' = '1' and password = 'admin' or '1' = '1'
select * from user where username = '1'' or ''1'' = ''1' and password = 'admin'' or ''1'' = ''1'
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命名)