linkin大话数据结构--apache commons工具类

Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动。

一、Commons BeanUtils

说明:针对Bean的一个工具集。由于Bean往往是有一堆get和set组成,所以BeanUtils也是在此基础上进行一些包装。

二、Commons CLI
说明:这是一个处理命令的工具。比如main方法输入的string[]需要解析。你可以预先定义好参数的规则,然后就可以调用CLI来解析。

三、Commons Codec
说明:这个工具是用来编码和解码的,包括Base64,URL,Soundx等等。用这个工具的人应该很清楚这些,我就不多介绍了。

四、Commons Collections
说明:你可以把这个工具看成是java.util的扩展。

五、Commons Configuration
说明:这个工具是用来帮助处理配置文件的,支持很多种存储方式

六、Commons DBCP
说明:Database Connection pool, Tomcat就是用的这个,不用我多说了吧,要用的自己去网站上看说明。

七、Commons DbUtils
说明:我以前在写数据库程序的时候,往往把数据库操作单独做一个包。DbUtils就是这样一个工具,以后开发不用再重复这样的工作了。值得一体的是,这个工具并不是现在流行的OR-Mapping工具(比如Hibernate),只是简化数据库操作,比如

七1、Commons FileUpload
说明:jsp的上传文件功能怎么做呢?

八、Commons HttpClient
说明:这个工具可以方便通过编程的方式去访问网站。

九、Commons IO
说明:可以看成是java.io的扩展,我觉得用起来非常方便。

十、Commons JXPath
说明:Xpath你知道吧,那么JXpath就是基于Java对象的Xpath,也就是用Xpath对Java对象进行查询。这个东西还是很有想像力的。

十一、Commons Lang
说明:这个工具包可以看成是对java.lang的扩展。提供了诸如StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils等工具类。

十二、Commons Logging
说明:你知道Log4j吗?

十三、Commons Math
说明:看名字你就应该知道这个包是用来干嘛的了吧。这个包提供的功能有些和Commons Lang重复了,但是这个包更专注于做数学工具,功能更强大。

十四、Commons Net
说明:这个包还是很实用的,封装了很多网络协议。
1. FTP
2. NNTP
3. SMTP
4. POP3
5. Telnet
6. TFTP
7. Finger
8. Whois
9. rexec/rcmd/rlogin
10. Time (rdate) and Daytime
11. Echo
12. Discard
13. NTP/SNTP

十五、Commons Validator
说明:用来帮助进行验证的工具。比如验证Email字符串,日期字符串等是否合法。

十六、Commons Virtual File System
说明:提供对各种资源的访问接口。支持的资源类型包括

1. CIFS
2. FTP
3. Local Files
4. HTTP and HTTPS
5. SFTP
6. Temporary Files
7. WebDAV
8. Zip, Jar and Tar (uncompressed, tgz or tbz2)
9. gzip and bzip2
10. res
11. ram
这个包的功能很强大,极大的简化了程序对资源的访问。


十七、Commons Transaction
说明:提供持久层事务支持

十六、Commons Proxy
说明: 动态代理,拦截器一类的东西

十八、Commons pool
说明: 创建新的对象并初始化的操作,可能会消耗很多的时间。
在需要频繁创建并使用这些对象的场景中,为了提供系统性能,通常的做法是,创建一个对象池,将一定数量的对象缓存到这个对象池中。
需要使用时直接从对象池中取出对象,使用完后将对象扔回到对象池中即可。
Apache的commons pool组件是我们实现对象池化技术的良好助手。

十九、Commons Launcher
说明:创建跨平台可执行程序

二十、Commons Bean Scripting Framework(BSF)
说明:是一个支持在Java应用程序内调用脚本语言 (Script),并且支持脚本语言直接访问Java对象和方法的一个开源项目。有了它 , 你就能在java application中使用javascript, Python, XSLT, Perl, tcl, ……等一大堆scripting language
. 反过来也可以,就是在这些scripting language中调用任何已经注册过了的JavaBean,java object。它提供了完整的API实现通过Java访问脚本语言的引擎。

二十一、Commons chain
说明: 可以在你需要定义和执行一些顺序操作的时候采用Commons Chain。

二十二、Commons Compress
说明: 是一个压缩、解压缩文件的类库。可以操作ar, cpio, Unix dump, tar, zip, gzip, XZ, Pack200 and bzip2格式的文件,功能比较强大


二十三、Commons Discovery
说明: 组件被用以查找可插拔接口的实现实例,它提供了一种通用的实例化这些实现的方式,而且可以管理单例(工厂)的生命周期。

二十四、 commons exec
说明: Apache Commons Exec 是 Apache 上的一个 Java 项目,提供一些常用的方法用来执行外部进程,如下面代码所示:

String line = "AcroRd32.exe /p /h " + file.getAbsolutePath();
CommandLine commandLine = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
executor.setWatchdog(watchdog);
int exitValue = executor.execute(commandLine);

二十五、commons jelly
说明:Jelly能够把XML转换成可执行代码,所以Jelly是一个基于XML与Java的脚本和处理引擎。 Jelly借鉴了JSP定指标签,Velocity, Cocoon和Xdoclet中的脚本引擎的许多优点。Jelly可以用在命令行,Ant或者Servlet之中。


Apache Commons包很强大的,这里我主要说几个常用的工具类:

1,BeanUtils copyProperties(java.lang.Object dest, java.lang.Object orig) 【Copy property values from the origin bean to the destination bean for all cases where the property names are the same。dest目标对象,orig原始对象】   使用这个方法的时候,会把后面那个对象所有的属性都会复制到前面的目标对象里面,有一点注意的时候,这个方法不能随便使用,要是自己写一个类,直接调用这个方法是不行的。他的源码里面有这个orig instanceof DynaBean判断,具体什么意思我也不知道。不过在j2ee中可以使用,因为玩的都是j2ee项目,所以一般都可以使用。

2,Commons Lang 说明:这个工具包可以看成是对java.lang的扩展。提供了诸如StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils等工具类。

跟java.lang这个包的作用类似,Commons Lang这一组API也是提供一些基础的、通用的操作和处理,如自动生成toString()的结果、自动实现hashCode()和equals()方法、数组操作、枚举、日期和时间的处理等等。
 
这一组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包提供处理日期和时间的功 能。

我们首先来看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 – 用于处理单词大小写、换行等。


  • 下面讲下最常用的两个类:ArrayUtils
package tz.web.dao.bean;
import org.apache.commons.lang.ArrayUtils;

public class Linkin 
{
    public static void main(String[] args) 
    {
        //定义一个数组
        int[] intArray1 = { 2, 4, 8, 16 };
        //打印数组
        System.out.println("intArray1: " + ArrayUtils.toString(intArray1));//{2,4,8,16}
        //查找数组
        System.out.println("intArray1 contains '8'? "+ ArrayUtils.contains(intArray1, 8));//true
        System.out.println("intArray1 index of '8'? "+ ArrayUtils.indexOf(intArray1, 8));//2
        System.out.println("intArray1 last index of '8'? "+ ArrayUtils.lastIndexOf(intArray1, 8));//2
        //克隆和反转
        int[] intArray3 = ArrayUtils.clone(intArray1);
        System.out.println("intArray3: " + ArrayUtils.toString(intArray3));//{2,4,8,16}
        ArrayUtils.reverse(intArray3);
        System.out.println("intArray3 reversed: "+ ArrayUtils.toString(intArray3));//{16,8,4,2}
        //简单类型到包装类型的包装
        Integer[] integerArray1 = ArrayUtils.toObject(intArray1);
        System.out.println("integerArray1: "+ ArrayUtils.toString(integerArray1));//{2,4,8,16}
        //定义2个数组
        String[] s1 = new String[]{"1","2","3"};
        String[] s2 = new String[]{"a","b","c"};
        //合并2个数组
        String[] s = (String[])ArrayUtils.addAll(s1,s2);
        for (int i=0;i<s.length;i++)
        {
        System.out.print(s[i]);//123abc
        }
        String str = ArrayUtils.toString(s);
        //截取字符串
        str = str.substring(1,str.length()-1);
        System.out.println(str+">>"+str.length());//1,2,3,a,b,c>>11
    }

}


  • StringUtils

处理文本对Java应用来说应该算是家常便饭了,在1.4出现之前,Java自身提供的API非常有限,如String、 StringTokenizer、StringBuffer,操作也比较单一。无非就是查找substring、分解、合并等等。到1.4的出现可以说 Java的文字处理上了一个台阶,因为它支持regular expression了。这可是个重量级而方便的东东啊,缺点是太复杂,学习起来有一定难度。相较而言,Jakarta Commons提供的StringUtils和WordUtils至今还维持着那种简洁而强大的美,使用起来也很顺手

package tz.web.dao.bean;
import org.apache.commons.lang.StringUtils;

public class Linkin 
{
    public static void main(String[] args) 
    {
        String str1 = "";   
        String str2 = " ";   
        String str3 = "	";   
        String str4 = null;   
        String str5 = "123";   
        String str6 = "ABCDEFG"; 
        //检查非空   下面4个都是true。对应的还有empty,别使用这个,这个不包含空格的。不为空的话前面加not就好了
        System.out.println("Is str1 blank? " + StringUtils.isBlank(str1)); 
        System.out.println("Is str2 blank? " + StringUtils.isBlank(str2));   
        System.out.println("Is str3 blank? " + StringUtils.isBlank(str3));   
        System.out.println("Is str4 blank? " + StringUtils.isBlank(str4));   
        //检查是不是数字  
        System.out.println("Is str5 numeric? " + StringUtils.isNumeric(str5)); //true  
        System.out.println("Is str6 numeric? " + StringUtils.isNumeric(str6)); // false
        //字符串的反转  
        System.out.println("str6 reversed: " + StringUtils.reverse(str6)); // GFEDCBA 
        //将数组转换成字符串,还可以加自己的分隔符
        String[] names = new String[]{"linkin1", "linkin2", "linkin3"};   
        System.out.println(StringUtils.join(names, ","));   //linkin1,linkin2,linkin3
<span style="white-space:pre">	</span>// 1 合并两个数组: org.apache.commons.lang. ArrayUtils
<span style="white-space:pre">		</span>// 有时我们需要将两个数组合并为一个数组,用ArrayUtils就非常方便,示例如下:
<span style="white-space:pre">		</span>private static void testArr() {
<span style="white-space:pre">			</span>String[] s1 = new String[] { "1", "2", "3" };
<span style="white-space:pre">			</span>String[] s2 = new String[] { "a", "b", "c" };
<span style="white-space:pre">			</span>String[] s = (String[]) ArrayUtils.addAll(s1, s2);
<span style="white-space:pre">			</span>for (int i = 0; i < s.length; i++) {
<span style="white-space:pre">				</span>System.out.println(s[i]);
<span style="white-space:pre">			</span>}
<span style="white-space:pre">			</span>String str = ArrayUtils.toString(s);
<span style="white-space:pre">			</span>str = str.substring(1, str.length() - 1);
<span style="white-space:pre">			</span>System.out.println(str + ">>" + str.length());


<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>//2 截取从from开始字符串
<span style="white-space:pre">		</span>StringUtils.substringAfter("SELECT * FROM PERSON ", "from");
<span style="white-space:pre">		</span>//3 判断该字符串是不是为数字(0~9)组成,如果是,返回true 但该方法不识别有小数点和 请注意
<span style="white-space:pre">		</span>StringUtils.isNumeric("454534"); //返回true
<span style="white-space:pre">		</span>//4.取得类名
        System.out.println(ClassUtils.getShortClassName(Test.class));
        //取得其包名
        System.out.println(ClassUtils.getPackageName(Test.class));
       
        //5.NumberUtils
        System.out.println(NumberUtils.stringToInt("6"));
        //6.五位的随机字母和数字
        System.out.println(RandomStringUtils.randomAlphanumeric(5));
        //7.StringEscapeUtils
        System.out.println(StringEscapeUtils.escapeHtml("<html>"));
        //输出结果为&lt;html&gt;
        System.out.println(StringEscapeUtils.escapeJava("String"));
       
        //8.StringUtils,判断是否是空格字符
        System.out.println(StringUtils.isBlank("   "));
        //将数组中的内容以,分隔
        System.out.println(StringUtils.join(test,","));
        //在右边加下字符,使之总长度为6
        System.out.println(StringUtils.rightPad("abc", 6, 'T'));
        //首字母大写
        System.out.println(StringUtils.capitalize("abc"));
        //Deletes all whitespaces from a String 删除所有空格
        System.out.println( StringUtils.deleteWhitespace("   ab  c  "));
        //判断是否包含这个字符
        System.out.println( StringUtils.contains("abc", "ba"));
        //表示左边两个字符
        System.out.println( StringUtils.left("abc", 2));
        System.out.println(NumberUtils.stringToInt("33"));
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"> }</span>
}


  • ListUtils
首先他有一个属性,EMPTY_LIST,它的源码如下:public static final List EMPTY_LIST = Collections.EMPTY_LIST,其实就是JDK中Collections的EMPTY_LIST。以后养成良好的习惯,比如我们在写一个接口的时候,返回值的类型是List,那么要是参数不符合情况时,我们就应该返回一个这个空集合。


package tz.web.dao.bean;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.collections.Bag;
import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.Buffer;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.IterableMap;
import org.apache.commons.collections.MapIterator;
import org.apache.commons.collections.OrderedMap;
import org.apache.commons.collections.bag.HashBag;
import org.apache.commons.collections.bidimap.TreeBidiMap;
import org.apache.commons.collections.buffer.UnboundedFifoBuffer;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections.map.LinkedMap;

public class Linkin 
{
    public static void main(String[] args) 
    {
        //通过Iterator遍历得到一个map里的key和value
        IterableMap map = new HashedMap();
        map.put("a","1");
        map.put("b",new Integer(2));
        MapIterator it = map.mapIterator();
        while (it.hasNext()) 
        {
        Object key = it.next();
        Object value = it.getValue();
        System.out.println(">>key>>"+key+">>value>>"+value);
        }
        
        //得到集合里按顺序存放的key之后的某一Key
        OrderedMap map1 = new LinkedMap();
        map1.put("FIVE", "5");
        map1.put("SIX", "6");
        map1.put("SEVEN", "7");
        map1.firstKey();  // returns "FIVE"
        map1.nextKey("FIVE");  // returns "SIX"
        map1.nextKey("SIX");  // returns "SEVEN"
        System.out.println(map1.firstKey()+">>"+map1.nextKey("FIVE")+">>"+map1.nextKey("SIX"));
        
        //通过key得到value        * 通过value得到key        * 将map里的key和value对调
        BidiMap bidi = new TreeBidiMap();
        bidi.put("SIX", "6");
        bidi.get("SIX");  // returns "6"
        bidi.getKey("6");  // returns "SIX"
        //bidi.removeValue("6");  // removes the mapping
        BidiMap inverse = bidi.inverseBidiMap();  // returns a map with keys and values swapped
        System.out.println(inverse);
        
        //移除集合某一元素并返回移除的元素
        Buffer buffer = new UnboundedFifoBuffer();
        buffer.add("ONE");
        buffer.add("TWO");
        buffer.add("THREE");
        System.out.println(buffer.remove());  // removes and returns the next in order, "ONE" as this is a FIFO
        System.out.println(buffer.remove());  // removes and returns the next in order, "TWO" as this is a FIFO
        System.out.println(buffer);
        
        //得到两个集合中相同的元素
        List<String> list1 = new ArrayList<String>();
        list1.add("1");
        list1.add("2");
        list1.add("3");
        List<String> list2 = new ArrayList<String>();
        list2.add("2");
        list2.add("3");
        list2.add("5");
        Collection c = CollectionUtils.retainAll(list1, list2);//
        System.out.println(c);
        
        //复制多个对象保存到Bag对象中
        Bag bag = new HashBag();
        bag.add("ONE", 6);  // add 6 copies of "ONE"
        bag.remove("ONE", 2);  // removes 2 copies of "ONE"
        System.out.println(bag.getCount("ONE"));  // returns 4, the number of copies in the bag (6 - 2)
        for (Iterator ite = bag.iterator();ite.hasNext();)
        {
        System.out.println(ite.next());
        }
    }
    
}
   
  • Logging 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

	public class CommonLogTest {
	 private static Log log = LogFactory.getLog(CommonLogTest.class);
	 //日志打印
	 public static void main(String[] args) {
		 log.error("ERROR");
		 log.debug("DEBUG");
		 log.warn("WARN");
		 log.info("INFO");
		 log.trace("TRACE");
	  System.out.println(log.getClass());
	 }

	}


原文地址:https://www.cnblogs.com/LinkinPark/p/5233130.html