常用工具类与commons 类库

Commons类库

commons: 一套开发源码、免费使用、商业友好的优秀API作为Java自带API的补充,大多数都是一些工具类 包括
  • Commons BeanUtils,针对Bean的一个工具集。由于Bean往往是有一堆get和set组成,所以BeanUtils也是在此基础上进行一些包装。
  • Commons CLI,这是一个处理命令的工具。比如main方法输入的string[]需要解析。你可以预先定义好参数的规则,然后就可以调用CLI来解析。
  • Commons Codec,这个工具是用来编码和解码的,包括Base64,URL,Soundx等等。
  • Commons Collections,可以把这个工具看成是java.util的扩展。
  • Commons Configuration,这个工具是用来帮助处理配置文件的,支持很多种存储方式
  • Commons DbUtils,DbUtils就是把数据库操作单独做一个包这样的工具,以后开发不用再重复这样的工作了。这个工具并不是现在流行的OR-Mapping工具(比如Hibernate),只是简化数据库操作
  • Commons FileUpload,文件上传。
  • Commons HttpClient,这个工具可以方便通过编程的方式去访问网站
  • Commons IO,可以看成是java.io的扩展
  • Commons JXPath,JXpath就是基于Java对象的Xpath,也就是用Xpath对Java对象进行查询
  • Commons Lang,这个工具包可以看成是对java.lang的扩展。提供了诸如StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils等工具类
  • Commons Logging,提供了log4j
  • Commons Math,这个包提供的功能有些和Commons Lang重复,但是这个包更专注于做数学工具,功能更强大
  • Commons Net,这个包还是很实用的,封装了很多网络协议
  • Commons Validator,用来帮助进行验证的工具。比如验证Email字符串,日期字符串等是否合法。
  • Commons virtual File System 提供对各种资源的访问接口。支持的资源类型包括
平时常用的是commons-lang、commons-collection、commons-beanutils、commons-codec、commons-io,Commons Logging。

commons-lang

  • Lang 主要是一些公共的工具集合,比如对字符、数组的操作等等

  • 可有效避免空指针异常

1.ArrayUtils

For Example

  • clone出一个新数组,相比list.addAll()不影响原数组
// 有时我们需要将两个数组合并为一个数组,用ArrayUtils就非常方便,示例如下:  
    private static void testArr() {  
        String[] s1 = new String[] { "1", "2", "3" };
        String[] s2 = new String[] { "a", "b", "c" };
        String[] s = (String[]) ArrayUtils.addAll(s1, s2);
        Stream.of(s).forEach(System.out::println);

        String str = ArrayUtils.toString(s);
        System.out.println(str + ">>" + str.length());
    }

所有方法

add,addAll,addFirst,clone,contains,copyArrayGrow1,getLength,hashCode,indexesOf,insert,isArrayIndexValid,isEmpty,isNotEmpty,isSameLength,isSorted,lastIndexOf,nullToEmpty,remove(针对index移除),removeAll(针多个index移除),removeAllOccurrences(针对值移除),removeElement(针对值移除第一次出现的值),removeElements(针对多个值移除第一次出现的值),reverse(逆转),shift(循环偏移),shuffle(随机排列),subarray,swap,toArray,toMap(遍历元素转换为map),toObject(将基本数据类型转为包装类),toPrimitive(将包装类转为基本类型),toString(可修改默认的‘{}’),toStringArray(每个元素toString)

2.StringUtils

For Example

  StringUtils.substringAfter("SELECT * FROM PERSON ", "FROM").trim();  
// 只能正整数.
  StringUtils.isNumeric("454534"); //返回true  
  StringUtils.equals("454534", "454534")
  StringUtils.equalsIgnoreCase("ABC534", "abc534")
  //判断是否是空格和null
  System.out.println(StringUtils.isBlank("   "));
  List<String> list = Lists.newArrayList("a", "b", "c");
  //将数组中的内容以,分隔
  System.out.println(StringUtils.join(list, ","));
  //在右边加下字符,使之总长度为6
  System.out.println(StringUtils.rightPad("123", 6, '0'));
  //首字母大写
  System.out.println(StringUtils.capitalize("abc"));
  //删除所有空格
  System.out.println( StringUtils.deleteWhitespace("   ab  c  "));
  //判断是否包含这个字符
  System.out.println( StringUtils.contains("abc", "ba"));
  //表示左边两个字符
  System.out.println(StringUtils.left("abc", 2));

所有方法

3.ClassUtils

   ClassUtils.getShortClassName(Test.class);  

   ClassUtils.getPackageName(Test.class);  
4.NumberUtils
  // 可以识别正负小数等 就别用stringutils里的isnumberic.
    System.out.println(NumberUtils.toInt("a", 0));
    System.out.println(NumberUtils.isNumber("-2.5"));
    System.out.println(NumberUtils.isNumber("2.5"));
5.RandomStringUtils
// 字母加数字
  System.out.println(RandomStringUtils.randomAlphanumeric(5));
// 字母
  System.out.println(RandomStringUtils.randomAlphabetic(5));
// 数字
  System.out.println(RandomStringUtils.randomNumeric(5));
6.StringEscapeUtils
 // 转义反转义
  System.out.println(StringEscapeUtils.escapeHtml("<html>"));
  System.out.println(StringEscapeUtils.unescapeHtml("<html>"));

commons-collection

Collections 对java.util的扩展封装,处理数据还是挺灵活的。 org.apache.commons.collections – Commons Collections自定义的一组公用的接口和工具类
  • bag – 实现Bag接口的一组类
  • bidimap – 实现BidiMap系列接口的一组类
  • buffer – 实现Buffer接口的一组类
  • collection – 实现java.util.Collection接口的一组类
  • comparators – 实现java.util.Comparator接口的一组类
  • functors – Commons Collections自定义的一组功能类
  • iterators – 实现java.util.Iterator接口的一组类
  • keyvalue – 实现集合和键/值映射相关的一组类
  • list – 实现java.util.List接口的一组类
  • map – 实现Map系列接口的一组类
  • set – 实现Set系列接口的一组类
    /**     **OrderedMap**
      得到集合里按顺序存放的key之后的某一Key
    */  
    OrderedMap map = new LinkedMap();
    map.put("FIVE", "5");
    map.put("SIX", "6");
    map.put("SEVEN", "7");
    System.out.println(map.firstKey());
    System.out.println(map.nextKey("FIVE"));
    System.out.println(map.nextKey("SIX"));
/**     **bidimap**
    * 通过key得到value
    * 通过value得到key
    * 将map里的key和value对调
    */      
    BidiMap bidi = new TreeBidiMap();
    bidi.put("SIX", "6");
    System.out.println(bidi.get("SIX"));  // returns "6"
    System.out.println(bidi.getKey("6"));  // returns "SIX"
    BidiMap inverse = bidi.inverseBidiMap();  // returns a map with keys and values swapped
    System.out.println(inverse);
    /**
    * 得到两个集合中相同的元素
    */  
    List<String> list1 = Lists.newArrayList("1", "2", "3");
    List<String> list2 = Lists.newArrayList("5", "2", "3");

    // 交集
    System.out.println(CollectionUtils.intersection(list1, list2));
    // 交集
    System.out.println(CollectionUtils.retainAll(list1, list2));
    // 并集
    System.out.println(CollectionUtils.union(list1, list2));
    // 减
    System.out.println(CollectionUtils.subtract(list1, list2));
    // 加
    CollectionUtils.addAll(list1, list2.iterator());
    System.out.println(list1);
    list2.add(null);
    System.out.println(list2);
    // 不为空才加
    list2.forEach(key -> CollectionUtils.addIgnoreNull(list1, key));
    System.out.println(list1);

commons-beanutils

BeanUtils 提供了对于JavaBean进行各种操作, 比如对象,属性复制等等。 1、对象的克隆
    xxx xxx = new xxx().setxxx(Lists.newArrayList("1", "2"))
                .xxx(2).xxx(1).xxx(Lists.newArrayList("ab", "bc"));
    try {
      //克隆,没克隆属性.
      xxx xxx =  (xxx) BeanUtils.cloneBean(xxx);
      System.out.println(xxx);
      // 不建议用apache赋值,会抛出异常,可用spring提供的不用try.注意参数顺序
      org.springframework.beans.BeanUtils.copyProperties(xxx, xxx);
      System.out.println(xxx);
    } catch (IllegalAccessException|InstantiationException|InvocationTargetException|NoSuchMethodException e) {
      e.printStackTrace();
    }
2、 将一个Map对象转化为一个Bean,通过Java的反射机制来做的。
    // 与lombok @Accessors(chain = true) 冲突.
    //这个Map对象的key必须与Bean的属性相对应.
    Map<String, Integer> map = Maps.newHashMap();
    map.put("xxx", 1);
    map.put("xxx", 2);

    //将map转化为对象属性.
    xxx xxx = new xxx();
    try {
        BeanUtils.populate(xxx, map);
        System.out.println(xxx);
        // 将对象转换为map.
        Map newMap = BeanUtils.describe(xxx);
        System.out.println(newMap);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        e.printStackTrace();
    }

    // 一般用spring提供的beantuils, 而且不会抛异常.

commons-codec

Codec 提供了一些公共的编解码实现,比如Base64, Hex, MD5,Phonetic and URLs等等。
    System.out.println(Base64.encodeBase64String("test".getBytes()));
    System.out.println(new String(Base64.decodeBase64("dGVzdA=="), StandardCharsets.UTF_8));
    System.out.println(DigestUtils.md5Hex("asdfasdfasdfasfdasdfasdfasfasd"));

    // 可以直接使用spring 提供的
    System.out.println(Base64Utils.encodeToString("absd".getBytes()));
    System.out.println(new String(Base64Utils.decodeFromString("YWJzZA=="), StandardCharsets.UTF_8));

common-io

IO 对java.io的扩展 操作文件非常方便。
    //1.读取Stream
    //标准代码:  
    try (InputStream in = new URL( "http://jakarta.apache.org" ).openStream()) {
        InputStreamReader inR = new InputStreamReader(in);
        BufferedReader buf = new BufferedReader(inR);
        String line;
        while ((line = buf.readLine()) != null) {
            System.out.println(line);
        }
    }
//使用IOUtils
    try (InputStream in = new URL( "http://www.baidu.com").openStream()) {
        System.out.println( IOUtils.toString(in, StandardCharsets.UTF_8));
    }

    //比较两个流是否相等
    InputStream in = new URL("http://www.baidu.com").openStream();
    InputStream in2 = new URL("http://www.baidu.com").openStream();
    System.out.println(IOUtils.contentEquals(in, in2));

    //将字节从InputStream复制到OutputStream或者是ByteArrayOutputStream
    File src = new File("D:/test.txt");
    InputStream inputStream = new FileInputStream(src);
    File dest = new File("D:/blank.txt");
    OutputStream outputStream = new FileOutputStream(dest);
    IOUtils.copy(inputStream, outputStream);

    //从输入流中读取字节(通常返回输入流的字节数组的长度)
    InputStream in4 = new URL("http://www.baidu.com").openStream();
    byte[] buffer = new byte[100000];
    System.out.println(IOUtils.read(in4, buffer));

    //获得输入流的内容放回一个List<String>类型的容器,每一行为这个容器的一个入口,使用特定的字符集(如果为空就使用默认的字符集)
    InputStream in5 = new URL("http://www.baidu.com").openStream();
    List<String> list = IOUtils.readLines(in5, StandardCharsets.UTF_8);
    Iterator<String> iter = list.iterator();
    while(iter.hasNext()){
        System.out.println(iter.next());
    }
//使用FileUtils
    File src = new File("D:/test.txt");
    List lines = FileUtils.readLines(src, "UTF-8");
    System.out.println(lines);

    File dest = new File("D:/blank.txt");
    //拷贝文件 --这里会覆盖--而非追加
    FileUtils.copyFile(src, dest);

    //拷贝文件到某一路径
    FileUtils.copyFileToDirectory(src, new File("E:/"));

    //写字符串到一个文件--此种为覆盖的方法
    String string = "Blah blah blah";
    FileUtils.writeStringToFile(dest, string, "ISO-8859-1");

    // 向文件追加内容.
    FileUtils.write(dest, "hhhhhhhhh", StandardCharsets.UTF_8, true);

    //删除文件实例
    File file = new File( ("E:/test.txt") );
    FileUtils.forceDelete(file);  

guava

  • java开源库,提供用于集合,缓存,支持原语,并发性,常见注解,字符串处理,I/O和验证的实用方法。
  • 标准化-由google托管
  • 高效、可靠
  • 优化-经过高度优化
<dependency> 
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
</dependency>

常用类与接口

1.集合的创建

// 普通Collection的创建 
List<String> list = Lists.newArrayList();
Set<String> set = Sets.newHashSet(); 
Map<String, String> map = Maps.newHashMap(); 

// 不变Collection的创建
***不可变集合***

* 在多线程操作下,是线程安全的。
* 所有不可变集合会比可变集合更有效的利用资源。
* 中途不可改变。

    ImmutableList<String> iList = ImmutableList.of("a", "b", "c");
    ImmutableSet<String> iSet = ImmutableSet.of("e1", "e2");
    ImmutableMap<String, String> iMap = ImmutableMap.of("k1", "v1", "k2", "v2");
    System.out.println(iList);
    System.out.println(iSet);
    System.out.println(iMap);
    iList.add("d");
/**
Exception in thread "main" java.lang.UnsupportedOperationException
    at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:202)
    at com.thunisoft.zx.zxznglxt.controller.SyncDataController.main(SyncDataController.java:62)
  **/
// **多值map,Multimap**
//以前
Map<String,List<Integer>> map = new HashMap<String,List<Integer>>(); 
List<Integer> list = new ArrayList<Integer>(); 
list.add(1); 
list.add(2); 
map.put("aa", list);
system.out.println(map.get("aa"));//[1, 2]
    Multimap<String,Integer> map = ArrayListMultimap.create();
    map.put("aa", 1);
    map.put("aa", 2);
    map.put("aa", 1);
    System.out.println(map.get("aa"));

    MultiKeyMap multiKeyMap = new MultiKeyMap();
    multiKeyMap.put("a","c", "b");
    System.out.println(multiKeyMap.get("a"));
    System.out.println(multiKeyMap.get("a", "c"));
    System.out.println(multiKeyMap.get("a", "d"));

    MultiValueMap multiValueMap = new MultiValueMap();
    multiValueMap.put("aa", 1);
    multiValueMap.put("aa", 2);
    multiValueMap.put("ab", 2);
    System.out.println(multiValueMap);
  • MultiSet: 无序+可重复 count()方法获取重复的次数 增强了可读性+操作简单
Multiset<Integer> set = HashMultiset.create();
for (int i=0;i<10;i++) {
    set.add(i%3);
}
System.out.println(set);
System.out.println(set.count(1));
System.out.println(set.count(3));
  • BiMap: 双向Map(Bidirectional Map) 键与值都不能重复
BiMap<String, String> biMap = HashBiMap.create();
biMap.put("a","1");
System.out.println(biMap);
System.out.println(biMap.inverse());

biMap.put("b", "1");
/**
Exception in thread "main" java.lang.IllegalArgumentException: value already present: 1
    at com.google.common.collect.HashBiMap.put(HashBiMap.java:285)
    at com.google.common.collect.HashBiMap.put(HashBiMap.java:260)
    at com.thunisoft.zx.zxznglxt.controller.SyncDataController.main(SyncDataController.java:69)
**/
  • Table: 双键的Map Map--> Table-->rowKey+columnKey+value //和sql中的联合主键有点像
Table<String, String, Integer> tables = HashBasedTable.create();
tables.put("a", "b", 3);
tables.put("a", "c", 4);
System.out.println(tables.get("a", "b"));
System.out.println(tables);
2.将集合转换为特定规则的字符串
//use guava 
List<String> list = Lists.newArrayList();
list.add("aa");
list.add("bb");
list.add("cc");
System.out.println(Joiner.on("-").join(list));
3.将String转换为特定的集合
//use guava 
String str = "1-2-3-4-5-6"; 
System.out.println(Splitter.on("-").splitToList(str)); //去除空格 .omitEmptyStrings().trimResults()
//list为 [1, 2, 3, 4, 5, 6]
4.将String转换为map
String str = "xiaoming=11,xiaohong=23";
System.out.println(Splitter.on(",").withKeyValueSeparator("=").split(str));
5.guava还支持多个字符切割,或者特定的正则分隔
String input = "aa.dd,,ff,,.";
System.out.println(Splitter.onPattern("[.|,]").omitEmptyStrings().splitToList(input));
6.set的交集, 并集, 差集
HashSet<Integer> setA = Sets.newHashSet(1, 2, 3, 4, 5);
HashSet<Integer> setB = Sets.newHashSet(4, 5, 6, 7, 8);
Sets.SetView<Integer> union = Sets.union(setA, setB);  //union:12345867
Sets.SetView<Integer> difference = Sets.difference(setA, setB); //difference:123678
Sets.SetView<Integer> symmetricDifference = Sets.symmetricDifference(setA, setB); //difference:123678
Sets.SetView<Integer> intersection = Sets.intersection(setA, setB); //intersection:45
System.out.println(union);
System.out.println(difference);
System.out.println(symmetricDifference);
System.out.println(intersection);
7.计算中间代码的运行时间
Stopwatch stopwatch = Stopwatch.createStarted();
TimeUnit.SECONDS.sleep(3);
long nanos = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println(nanos);


查看原文:http://yuyy.info/?p=1200
原文地址:https://www.cnblogs.com/yuyy114/p/13246723.html