Apache Commons 工具类介绍,apachecommons


# 1. Apache Commons Lang (Java基本对象方法的工具类包)
## 合并两个数组: org.apache.commons.lang.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);  
            for (int i = 0; i < s.length; i++) {  
                System.out.println(s[i]);  
            }  
            String str = ArrayUtils.toString(s);  
            str = str.substring(1, str.length() - 1);  
            System.out.println(str + ">>" + str.length());  
      
        }



## 截取从from开始字符串
StringUtils.substringAfter("SELECT * FROM PERSON ", "FROM");
## 判断字符串是不是为数字(0~9)组成,如果是,返回true 但该方法不识别有小数点
StringUtils.isNumeric("454534"); //返回true
## 取得类名
System.out.println(ClassUtils.getShortClassName(Test.class)); //取得其包名 System.out.println(ClassUtils.getPackageName(Test.class));
## 五位的随机字母和数字
System.out.println(RandomStringUtils.randomAlphanumeric(5));
## 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"));



## NumberUtils用法
/*1. NumberUtils.isNumber() : 判断字符串是否是数字*/
  NumberUtils.isNumber("5.96");//结果是true
  NumberUtils.isNumber("s5");//结果是false
  NumberUtils.isNumber("0000000000596");//结果是true
  /*2. NumberUtils.isDigits() :判断字符串中是否全为数字*/
  NumberUtils.isDigits("0000000000.596");//false
  NumberUtils.isDigits("0000000000596");//true
  /*3. NumberUtils.toInt() :字符串转换为数字*/
  NumberUtils.toInt("5");
  NumberUtils.toLong("5");
  NumberUtils.toByte("3");
  NumberUtils.toFloat("");
  NumberUtils.toDouble("4");
  NumberUtils.toShort("3");
  /*4. NumberUtils.max() :找出最大的一个*/
  NumberUtils.max(new int[]{3,5,6});//结果是6
  NumberUtils.max(3, 1, 7);//结果是7
  /*5. NumberUtils.min() :找出最小的一个*/
  NumberUtils.min(new int[]{3,5,6});//结果是6
  NumberUtils.min(3, 1, 7);//结果是7




# 2. Apache Commons Compress (提供文件打包 压缩类库)
//创建压缩对象  
ZipArchiveEntry entry = new ZipArchiveEntry("CompressTest");  
//要压缩的文件  
File f=new File("e:\\test.pdf");  
FileInputStream fis=new FileInputStream(f);  
//输出的对象 压缩的文件  
ZipArchiveOutputStream zipOutput=new ZipArchiveOutputStream(new File("e:\\test.zip"));  
zipOutput.putArchiveEntry(entry);  
int i=0,j;  
while((j=fis.read()) != -1)  
{   
zipOutput.write(j);  
i++;  
System.out.println(i);  
}  
zipOutput.closeArchiveEntry();  
zipOutput.close();  
fis.close();




# 3. Apache Commons Collections (对java.util的扩展封装)
## 得到集合里按顺序存放的key之后的某一Key
OrderedMap map = new LinkedMap();  
    map.put("FIVE", "5");  
    map.put("SIX", "6");  
    map.put("SEVEN", "7");  
    map.firstKey(); // returns "FIVE"  
    map.nextKey("FIVE"); // returns "SIX"  
    map.nextKey("SIX"); // returns "SEVEN"


## 通过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);



## 得到两个集合中相同的元素
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);




# 4. Apache Commons IO
## 读取Stream
//标准代码:  
InputStream in = new URL( "http://jakarta.apache.org" ).openStream();  
try {  
       InputStreamReader inR = new InputStreamReader( in );  
       BufferedReader buf = new BufferedReader( inR );  
       String line;  
       while ( ( line = buf.readLine() ) != null ) {  
          System.out.println( line );  
       }  
  } finally {  
    in.close();  
  }  
  
//使用IOUtils  
InputStream in = new URL( "http://jakarta.apache.org" ).openStream();  
try {  
    System.out.println( IOUtils.toString( in ) );  
} finally {  
    IOUtils.closeQuietly(in);  
}  


## 读取文件 File file = new File("/commons/io/project.properties"); List lines = FileUtils.readLines(file, "UTF-8"); ## 察看剩余空间 long freeSpace = FileSystemUtils.freeSpace("C:/");

# 5. Apache Commons Configuration (用来帮助处理配置文件的,支持很多种存储方式)
//举一个Properties的简单例子  
    # usergui.properties  
    colors.background = #FFFFFF  
    colors.foreground = #000080  
    window.width = 500  
    window.height = 300  
      
    PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");  
    config.setProperty("colors.background", "#000000);  
    config.save();  
      
    config.save("usergui.backup.properties);//save a copy  
    Integer integer = config.getInteger("window.width");




# 6. Apache Commons Email
//用commons email发送邮件  
    public static void main(String args[]){  
            Email email = new SimpleEmail();  
            email.setHostName("smtp.googlemail.com");  
            email.setSmtpPort(465);  
            email.setAuthenticator(new DefaultAuthenticator("username", "password"));  
            email.setSSLOnConnect(true);  
            email.setFrom("user@gmail.com");  
            email.setSubject("TestMail");  
            email.setMsg("This is a test mail ... :-)");  
            email.addTo("foo@bar.com");  
            email.send();  
        }  




# 7. Apache Commons DBCP(Database Connection Pool是一个依赖Jakarta commons-pool对象池机制的数据库连接池, Tomcat的数据源使用的就是DBCP)
//官方示例  
    public class PoolingDataSources {  
      
        public static void main(String[] args) {  
            System.out.println("加载jdbc驱动");  
            try {  
            Class.forName("oracle.jdbc.driver.OracleDriver");  
            } catch (ClassNotFoundException e) {  
            e.printStackTrace();  
            }  
            System.out.println("Done.");  
            //  
            System.out.println("设置数据源");  
            DataSource dataSource = setupDataSource("jdbc:oracle:thin:@localhost:1521:test");  
            System.out.println("Done.");  
              
            //  
            Connection conn = null;  
            Statement stmt = null;  
            ResultSet rset = null;  
              
            try {  
            System.out.println("Creating connection.");  
            conn = dataSource.getConnection();  
            System.out.println("Creating statement.");  
            stmt = conn.createStatement();  
            System.out.println("Executing statement.");  
            rset = stmt.executeQuery("select * from person");  
            System.out.println("Results:");  
            int numcols = rset.getMetaData().getColumnCount();  
            while(rset.next()) {  
            for(int i=0;i<=numcols;i++) {  
            System.out.print("\t" + rset.getString(i));  
            }  
            System.out.println("");  
            }  
            } catch(SQLException e) {  
            e.printStackTrace();  
            } finally {  
            try { if (rset != null) rset.close(); } catch(Exception e) { }  
            try { if (stmt != null) stmt.close(); } catch(Exception e) { }  
            try { if (conn != null) conn.close(); } catch(Exception e) { }  
            }  
            }  
      
        public static DataSource setupDataSource(String connectURI) {  
            //设置连接地址  
            ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(  
                    connectURI, null);  
      
            // 创建连接工厂  
            PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(  
                    connectionFactory);  
      
            //获取GenericObjectPool 连接的实例  
            ObjectPool connectionPool = new GenericObjectPool(  
                    poolableConnectionFactory);  
      
            // 创建 PoolingDriver  
            PoolingDataSource dataSource = new PoolingDataSource(connectionPool);  
              
            return dataSource;  
        }  
    }



# 8. Apache Commons Math (Commons Math 是 Apache 上一个轻量级自容器的数学和统计计算方法包,包含大多数常用的数值算法)
示例代码:
// 创建一个具有两行三列的实矩阵
double[][] matrixData = { {1d,2d,3d}, {2d,5d,3d}};
RealMatrix m = new Array2DRowRealMatrix(matrixData);

// One more with three rows, two columns
double[][] matrixData2 = { {1d,2d}, {2d,5d}, {1d, 7d}};
RealMatrix n = new Array2DRowRealMatrix(matrixData2);

// Note: 构造函数复制输入的[ [] ]数组.

// m乘n
RealMatrix p = m.multiply(n);
System.out.println(p.getRowDimension());    // 2
System.out.println(p.getColumnDimension()); // 2

// 用LU分解法反演p
RealMatrix pInverse = new LUDecompositionImpl(p).getSolver().getInverse();




# 9. Apache Commons Pool(Commons Pool组件提供了一整套用于实现对象池化的框架,以及若干种各具特色的对象池实现, 可以有效地减少处理对象池化时的工作量,显著的提升了性能和可伸缩性,特别是在高并发加载的情况下)
代码示例参考: http://commons.apache.org/proper/commons-pool/examples.html
# 10. Apache Commons Exec (是一个在JVM中执行外部进程的库)
代码示例参考: http://commons.apache.org/proper/commons-exec/tutorial.html 官方教程提供的非堵塞方法在1.3版中不适用
# 11. Apache Commons CSV (是一个用来读写各种 Comma Separated Value (CSV)格式文件的Java库)
代码示例参考: http://www.oschina.net/p/commons-csv http://www.what21.com/programming/java/apache/csv.html
# 12. Commons JEXL (是带有扩展的JSTL表达式语言的实现)
# 13. Apache Commons VFS
# 14. Apache Commons Text (实现了一系列关于文本字符串的算法,专注于处理字符串和文本块)
# 15. Apache Commons Digester (Digester 是一个基于规则的XML文档解析库,主要用于XML到Java对象的映射。 Struts就是用Digester来处理XML配置文件的。而且Digester还包含一个写好的RSS解析器)
# 16. com.springsource.org.apache.commons.logging 个人觉得相当于Log4j的作用
# 17. Commons Proxy (用于动态代理的Java库)
# 18. Commons RDF:API
# 19. Apache Commons JCI Core (Apache Commons JCI核心接口和实现)

相关内容

    暂无相关文章