Apache Commons 工具類介紹及簡單使用

個(gè)人專題目錄


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

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

BeanUtils

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

Java代碼

//  新創(chuàng)建一個(gè)普通Java Bean,用來作為被克隆的對象
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();
}
//  原理也是通過Java的反射機(jī)制來做的。
//  2、 將一個(gè)Map對象轉(zhuǎn)化為一個(gè)Bean
//  這個(gè)Map對象的key必須與Bean的屬性相對應(yīng)。
Map map = new HashMap();
map.put("name", "tom");
map.put("email", "tom@");
map.put("age", "21");
//將map轉(zhuǎn)化為一個(gè)Person對象
Person person = new Person();
BeanUtils.populate(person, map);
//  通過上面的一行代碼,此時(shí)person的屬性就已經(jīng)具有了上面所賦的值了。
//  將一個(gè)Bean轉(zhuǎn)化為一個(gè)Map對象了,如下:
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

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

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

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"

/**
 * 通過key得到value
 * 通過value得到key
 * 將map里的key和value對調(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中的打包、壓縮類庫。

Java代碼

//創(chuàng)建壓縮對象
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();

Configuration

用來幫助處理配置文件的,支持很多種存儲(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的簡單例子  
# 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è)依賴Jakarta commons-pool對象池機(jī)制的數(shù)據(jù)庫連接池,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工具類庫,它是對JDBC的簡單封裝,對傳統(tǒng)操作數(shù)據(jù)庫的類進(jìn)行二次封裝,可以把結(jié)果集轉(zhuǎn)化成List。,同時(shí)也不影響程序的性能。

DbUtils類:啟動(dòng)類

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

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

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

Qrery Runner類:執(zhí)行SQL語句的類

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)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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

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