Apache Commons 工具類(lèi)介紹及簡(jiǎn)單使用

個(gè)人專(zhuān)題目錄


Apache Commons包含了很多開(kāi)源的工具,用于解決平時(shí)編程經(jīng)常會(huì)遇到的問(wèn)題,減少重復(fù)勞動(dòng)。下面是我這幾年做開(kāi)發(fā)過(guò)程中自己用過(guò)的工具類(lèi)做簡(jiǎn)單介紹。

組件 功能介紹
BeanUtils 提供了對(duì)于JavaBean進(jìn)行各種操作,克隆對(duì)象,屬性等等.
Betwixt XML與Java對(duì)象之間相互轉(zhuǎn)換.
Codec 處理常用的編碼方法的工具類(lèi)包 例如DES、SHA1、MD5、Base64等.
Collections java集合框架操作.
Compress java提供文件打包 壓縮類(lèi)庫(kù).
Configuration 一個(gè)java應(yīng)用程序的配置管理類(lèi)庫(kù).
DBCP 提供數(shù)據(jù)庫(kù)連接池服務(wù).
DbUtils 提供對(duì)jdbc 的操作封裝來(lái)簡(jiǎn)化數(shù)據(jù)查詢(xún)和記錄讀取操作.
Email java發(fā)送郵件 對(duì)javamail的封裝.
FileUpload 提供文件上傳功能.
HttpClien 提供HTTP客戶(hù)端與服務(wù)器的各種通訊操作. 現(xiàn)在已改成HttpComponents
IO io工具的封裝.
Lang Java基本對(duì)象方法的工具類(lèi)包 如:StringUtils,ArrayUtils等等.
Logging 提供的是一個(gè)Java 的日志接口.
Validator 提供了客戶(hù)端和服務(wù)器端的數(shù)據(jù)驗(yàn)證框架.

BeanUtils

提供了對(duì)于JavaBean進(jìn)行各種操作, 比如對(duì)象,屬性復(fù)制等等。

Java代碼

//  新創(chuàng)建一個(gè)普通Java Bean,用來(lái)作為被克隆的對(duì)象
public class Person {
    private String name = "";
    private String email = "";

    private int age;
    //省略 set,get方法
}
Person person = new Person();
person.setName("tom");
person.setAge(21);
try {
    //克隆
    Person person2 = (Person) BeanUtils.cloneBean(person);
    System.out.println(person2.getName() + ">>" + person2.getAge());
} catch (
        IllegalAccessException e) {
    e.printStackTrace();
} catch (InstantiationException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}
//  原理也是通過(guò)Java的反射機(jī)制來(lái)做的。
//  2、 將一個(gè)Map對(duì)象轉(zhuǎn)化為一個(gè)Bean
//  這個(gè)Map對(duì)象的key必須與Bean的屬性相對(duì)應(yīng)。
Map map = new HashMap();
map.put("name", "tom");
map.put("email", "tom@");
map.put("age", "21");
//將map轉(zhuǎn)化為一個(gè)Person對(duì)象
Person person = new Person();
BeanUtils.populate(person, map);
//  通過(guò)上面的一行代碼,此時(shí)person的屬性就已經(jīng)具有了上面所賦的值了。
//  將一個(gè)Bean轉(zhuǎn)化為一個(gè)Map對(duì)象了,如下:
Map map = BeanUtils.describe(person)

Codec

提供了一些公共的編解碼實(shí)現(xiàn),比如Base64, Hex, MD5,Phonetic and URLs等等。

Java代碼

//Base64編解碼
private static String encodeTest(String str) {
    Base64 base64 = new Base64();
    try {
        str = base64.encodeToString(str.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    System.out.println("Base64 編碼后:" + str);
    return str;
}

private static void decodeTest(String str) {
    Base64 base64 = new Base64();
    //str = Arrays.toString(Base64.decodeBase64(str));
    str = new String(Base64.decodeBase64(str));
    System.out.println("Base64 解碼后:" + str);
}

Collections

對(duì)java.util的擴(kuò)展封裝,處理數(shù)據(jù)還是挺靈活的。

org.apache.commons.collections – Commons Collections自定義的一組公用的接口和工具類(lèi)
org.apache.commons.collections.bag – 實(shí)現(xiàn)Bag接口的一組類(lèi)
org.apache.commons.collections.bidimap – 實(shí)現(xiàn)BidiMap系列接口的一組類(lèi)
org.apache.commons.collections.buffer – 實(shí)現(xiàn)Buffer接口的一組類(lèi)
org.apache.commons.collections.collection – 實(shí)現(xiàn)java.util.Collection接口的一組類(lèi)
org.apache.commons.collections.comparators – 實(shí)現(xiàn)java.util.Comparator接口的一組類(lèi)
org.apache.commons.collections.functors – Commons Collections自定義的一組功能類(lèi)
org.apache.commons.collections.iterators – 實(shí)現(xiàn)java.util.Iterator接口的一組類(lèi)
org.apache.commons.collections.keyvalue – 實(shí)現(xiàn)集合和鍵/值映射相關(guān)的一組類(lèi)
org.apache.commons.collections.list – 實(shí)現(xiàn)java.util.List接口的一組類(lèi)
org.apache.commons.collections.map – 實(shí)現(xiàn)Map系列接口的一組類(lèi)
org.apache.commons.collections.set – 實(shí)現(xiàn)Set系列接口的一組類(lèi)

Java代碼

/**
 * 得到集合里按順序存放的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"

/**
 * 通過(guò)key得到value
 * 通過(guò)value得到key
 * 將map里的key和value對(duì)調(diào)
 */
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);

/**
 * 得到兩個(gè)集合中相同的元素
 */
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);

Compress

commons compress中的打包、壓縮類(lèi)庫(kù)。

Java代碼

//創(chuàng)建壓縮對(duì)象
ZipArchiveEntry entry = new ZipArchiveEntry("CompressTest");
//要壓縮的文件
File f = new File("e:\test.pdf");
FileInputStream fis = new FileInputStream(f);
//輸出的對(duì)象 壓縮的文件
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();

Configuration

用來(lái)幫助處理配置文件的,支持很多種存儲(chǔ)方式。

1. Properties files
2. XML documents
3. Property list files (.plist)
4. JNDI
5. JDBC Datasource
6. System properties
7. Applet parameters
8. Servlet parameters

Java代碼

//舉一個(gè)Properties的簡(jiǎn)單例子  
# 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");

DBCP

(Database Connection Pool)是一個(gè)依賴(lài)Jakarta commons-pool對(duì)象池機(jī)制的數(shù)據(jù)庫(kù)連接池,Tomcat的數(shù)據(jù)源使用的就是DBCP。

//官方示例
    public class PoolingDataSources {

        public static void main(String[] args) {
            System.out.println("加載jdbc驅(qū)動(dòng)");
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            System.out.println("Done.");
            //
            System.out.println("設(shè)置數(shù)據(jù)源");
            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) {
            //設(shè)置連接地址
            ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                    connectURI, null);

            // 創(chuàng)建連接工廠
            PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                    connectionFactory);

            //獲取GenericObjectPool 連接的實(shí)例
            ObjectPool connectionPool = new GenericObjectPool(
                    poolableConnectionFactory);

            // 創(chuàng)建 PoolingDriver
            PoolingDataSource dataSource = new PoolingDataSource(connectionPool);

            return dataSource;
        }
    }

DbUtils

Apache組織提供的一個(gè)資源JDBC工具類(lèi)庫(kù),它是對(duì)JDBC的簡(jiǎn)單封裝,對(duì)傳統(tǒng)操作數(shù)據(jù)庫(kù)的類(lèi)進(jìn)行二次封裝,可以把結(jié)果集轉(zhuǎn)化成List。,同時(shí)也不影響程序的性能。

DbUtils類(lèi):?jiǎn)?dòng)類(lèi)

ResultSetHandler接口:轉(zhuǎn)換類(lèi)型接口

MapListHandler類(lèi):實(shí)現(xiàn)類(lèi),把記錄轉(zhuǎn)化成List

BeanListHandler類(lèi):實(shí)現(xiàn)類(lèi),把記錄轉(zhuǎn)化成List,使記錄為JavaBean類(lèi)型的對(duì)象

Qrery Runner類(lèi):執(zhí)行SQL語(yǔ)句的類(lèi)

public class BeanLists {
        public static void main(String[] args) {
            Connection conn = null;
            String url = "jdbc:mysql://localhost:3306/ptest";
            String jdbcDriver = "com.mysql.jdbc.Driver";
            String user = "root";
            String password = "ptest";

            DbUtils.loadDriver(jdbcDriver);
            try {
                conn = DriverManager.getConnection(url, user, password);
                QueryRunner qr = new QueryRunner();
                List results = (List) qr.query(conn, "select id,name from person", new BeanListHandler(Person.class));
                for (int i = 0; i < results.size(); i++) {
                    Person p = (Person) results.get(i);
                    System.out.println("id:" + p.getId() + ",name:" + p.getName());
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                DbUtils.closeQuietly(conn);
            }
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評(píng)論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類(lèi)相關(guān)的語(yǔ)法,內(nèi)部類(lèi)的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線(xiàn)程的語(yǔ)...
    子非魚(yú)_t_閱讀 34,853評(píng)論 18 399
  • //Clojure入門(mén)教程: Clojure – Functional Programming for the J...
    葡萄喃喃囈語(yǔ)閱讀 4,078評(píng)論 0 7
  • 距離下一個(gè)讀書(shū)日還有366天,但距離上一個(gè)讀書(shū)日已經(jīng)過(guò)去365天。 一、我們需要通過(guò)閱讀書(shū)籍來(lái)為我們的實(shí)踐提供穩(wěn)固...
    不安分的不二閱讀 5,319評(píng)論 1 5
  • 愛(ài)情來(lái)之前,我們總會(huì)對(duì)自己未來(lái)的另一半設(shè)有各種各樣的條條框框,身高啊,體重啊,相貌啊……,愛(ài)情來(lái)臨時(shí),你才會(huì)發(fā)現(xiàn),...
    安暖mio閱讀 217評(píng)論 0 0

友情鏈接更多精彩內(nèi)容