欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java常用類庫(kù)Apache Commons工具類說(shuō)明及使用實(shí)例詳解

 更新時(shí)間:2020年02月20日 09:20:27   作者:挽星  
這篇文章主要介紹了Java常用類庫(kù)Apache Commons工具類說(shuō)明及使用實(shí)例詳解,需要的朋友可以參考下

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

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

1、BeanUtils 

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

//1、 克隆對(duì)象 
  // 新創(chuàng)建一個(gè)普通Java Bean,用來(lái)作為被克隆的對(duì)象 
   
    public class Person { 
    private String name = ""; 
    private String email = ""; 
   
    private int age; 
    //省略 set,get方法 
    } 
   
  // 再創(chuàng)建一個(gè)Test類,其中在main方法中代碼如下: 
    import java.lang.reflect.InvocationTargetException; 
    import java.util.HashMap; 
    import java.util.Map; 
    import org.apache.commons.beanutils.BeanUtils; 
    import org.apache.commons.beanutils.ConvertUtils; 
    public class Test { 
   
    /** 
   
    * @param args 
   
    */ 
    public static void main(String[] args) { 
    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)

2、Betwixt  

XML與Java對(duì)象之間相互轉(zhuǎn)換。

//1、 將JavaBean轉(zhuǎn)為XML內(nèi)容 
    // 新創(chuàng)建一個(gè)Person類 
    public class Person{ 
      private String name; 
      private int age; 
      /** Need to allow bean to be created via reflection */ 
      public PersonBean() { 
      } 
      public PersonBean(String name, int age) { 
        this.name = name; 
        this.age = age; 
      } 
      //省略set, get方法 
      public String toString() { 
        return "PersonBean[name='" + name + "',age='" + age + "']"; 
      } 
    } 
     
    //再創(chuàng)建一個(gè)WriteApp類: 
    import java.io.StringWriter; 
    import org.apache.commons.betwixt.io.BeanWriter; 
    public class WriteApp { 
    /** 
    * 創(chuàng)建一個(gè)例子Bean,并將它轉(zhuǎn)化為XML. 
    */ 
    public static final void main(String [] args) throws Exception { 
      // 先創(chuàng)建一個(gè)StringWriter,我們將把它寫(xiě)入為一個(gè)字符串     
      StringWriter outputWriter = new StringWriter(); 
      // Betwixt在這里僅僅是將Bean寫(xiě)入為一個(gè)片斷 
      // 所以如果要想完整的XML內(nèi)容,我們應(yīng)該寫(xiě)入頭格式 
      outputWriter.write(“<?xml version='1.0′ encoding='UTF-8′ ?>\n”); 
      // 創(chuàng)建一個(gè)BeanWriter,其將寫(xiě)入到我們預(yù)備的stream中 
      BeanWriter beanWriter = new BeanWriter(outputWriter); 
      // 配置betwixt 
      // 更多詳情請(qǐng)參考java docs 或最新的文檔 
      beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false); 
      beanWriter.getBindingConfiguration().setMapIDs(false); 
      beanWriter.enablePrettyPrint(); 
      // 如果這個(gè)地方不傳入XML的根節(jié)點(diǎn)名,Betwixt將自己猜測(cè)是什么 
      // 但是讓我們將例子Bean名作為根節(jié)點(diǎn)吧 
      beanWriter.write(“person”, new PersonBean(“John Smith”, 21)); 
      //輸出結(jié)果 
      System.out.println(outputWriter.toString()); 
      // Betwixt寫(xiě)的是片斷而不是一個(gè)文檔,所以不要自動(dòng)的關(guān)閉掉writers或者streams, 
      //但這里僅僅是一個(gè)例子,不會(huì)做更多事情,所以可以關(guān)掉 
      outputWriter.close(); 
      } 
    } 
  //2、 將XML轉(zhuǎn)化為JavaBean 
    import java.io.StringReader; 
    import org.apache.commons.betwixt.io.BeanReader; 
    public class ReadApp { 
    public static final void main(String args[]) throws Exception{ 
      // 先創(chuàng)建一個(gè)XML,由于這里僅是作為例子,所以我們硬編碼了一段XML內(nèi)容 
      StringReader xmlReader = new StringReader( 
      "<?xml version='1.0′ encoding='UTF-8′ ?> <person><age>25</age><name>James Smith</name></person>"); 
      //創(chuàng)建BeanReader 
      BeanReader beanReader = new BeanReader(); 
      //配置reader 
      beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false); 
      beanReader.getBindingConfiguration().setMapIDs(false); 
      //注冊(cè)beans,以便betwixt知道XML將要被轉(zhuǎn)化為一個(gè)什么Bean 
      beanReader.registerBeanClass("person", PersonBean.class); 
      //現(xiàn)在我們對(duì)XML進(jìn)行解析 
      PersonBean person = (PersonBean) beanReader.parse(xmlReader); 
      //輸出結(jié)果 
      System.out.println(person); 
      } 
    }

3、Codec 

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

//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); 
    }

4、Collections

 對(duì)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系列接口的一組類

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

5、Compress 

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

//創(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();

6、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

//舉一個(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");

7、DBCP  

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

import javax.sql.DataSource; 
  import java.sql.Connection; 
  import java.sql.Statement; 
  import java.sql.ResultSet; 
  import java.sql.SQLException; 
   
  import org.apache.commons.pool.ObjectPool; 
  import org.apache.commons.pool.impl.GenericObjectPool; 
  import org.apache.commons.dbcp.ConnectionFactory; 
  import org.apache.commons.dbcp.PoolingDataSource; 
  import org.apache.commons.dbcp.PoolableConnectionFactory; 
  import org.apache.commons.dbcp.DriverManagerConnectionFactory; 
  //官方示例 
  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; 
    } 
  }

8、DbUtils 

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

DbUtils類:?jiǎn)?dòng)類

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

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

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

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

import org.apache.commons.dbutils.DbUtils; 
  import org.apache.commons.dbutils.QueryRunner; 
  import org.apache.commons.dbutils.handlers.BeanListHandler; 
  import java.sql.Connection; 
  import java.sql.DriverManager; 
  import java.sql.SQLException; 
  import java.util.List; 
  //轉(zhuǎn)換成list 
  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); 
      } 
    } 
  } 
   
  public class Person{ 
    private Integer id; 
    private String name; 
   
    //省略set, get方法 
  } 
   
  import org.apache.commons.dbutils.DbUtils; 
  import org.apache.commons.dbutils.QueryRunner; 
  import org.apache.commons.dbutils.handlers.MapListHandler; 
   
  import java.sql.Connection; 
  import java.sql.DriverManager; 
  import java.sql.SQLException; 
   
  import java.util.List; 
  import java.util.Map; 
  //轉(zhuǎn)換成map 
  public class MapLists { 
    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 MapListHandler()); 
        for (int i = 0; i < results.size(); i++) { 
          Map map = (Map) results.get(i); 
          System.out.println("id:" + map.get("id") + ",name:" + map.get("name")); 
        } 
      } catch (SQLException e) { 
        e.printStackTrace(); 
      } finally { 
        DbUtils.closeQuietly(conn); 
      } 
    } 
  }

9、Email 

提供的一個(gè)開(kāi)源的API,是對(duì)javamail的封裝。

//用commons email發(fā)送郵件 
  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(); 
    }

10、FileUpload

 java web文件上傳功能。

//官方示例: 
  //* 檢查請(qǐng)求是否含有上傳文件 
    // Check that we have a file upload request 
    boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
   
    //現(xiàn)在我們得到了items的列表 
   
    //如果你的應(yīng)用近于最簡(jiǎn)單的情況,上面的處理就夠了。但我們有時(shí)候還是需要更多的控制。 
    //下面提供了幾種控制選擇: 
    // Create a factory for disk-based file items 
    DiskFileItemFactory factory = new DiskFileItemFactory(); 
   
    // Set factory constraints 
    factory.setSizeThreshold(yourMaxMemorySize); 
    factory.setRepository(yourTempDirectory); 
   
    // Create a new file upload handler 
    ServletFileUpload upload = new ServletFileUpload(factory); 
   
    // 設(shè)置最大上傳大小 
    upload.setSizeMax(yourMaxRequestSize); 
   
    // 解析所有請(qǐng)求 
    List /* FileItem */ items = upload.parseRequest(request); 
   
    // Create a factory for disk-based file items 
    DiskFileItemFactory factory = new DiskFileItemFactory( 
        yourMaxMemorySize, yourTempDirectory); 
   
    //一旦解析完成,你需要進(jìn)一步處理item的列表。 
    // Process the uploaded items 
    Iterator iter = items.iterator(); 
    while (iter.hasNext()) { 
      FileItem item = (FileItem) iter.next(); 
   
      if (item.isFormField()) { 
        processFormField(item); 
      } else { 
        processUploadedFile(item); 
      } 
    } 
   
    //區(qū)分?jǐn)?shù)據(jù)是否為簡(jiǎn)單的表單數(shù)據(jù),如果是簡(jiǎn)單的數(shù)據(jù): 
    // processFormField 
    if (item.isFormField()) { 
      String name = item.getFieldName(); 
      String value = item.getString(); 
      //...省略步驟 
    } 
   
    //如果是提交的文件: 
    // processUploadedFile 
    if (!item.isFormField()) { 
      String fieldName = item.getFieldName(); 
      String fileName = item.getName(); 
      String contentType = item.getContentType(); 
      boolean isInMemory = item.isInMemory(); 
      long sizeInBytes = item.getSize(); 
      //...省略步驟 
    } 
   
    //對(duì)于這些item,我們通常要把它們寫(xiě)入文件,或轉(zhuǎn)為一個(gè)流 
    // Process a file upload 
    if (writeToFile) { 
      File uploadedFile = new File(...); 
      item.write(uploadedFile); 
    } else { 
      InputStream uploadedStream = item.getInputStream(); 
      //...省略步驟 
      uploadedStream.close(); 
    } 
   
    //或轉(zhuǎn)為字節(jié)數(shù)組保存在內(nèi)存中: 
    // Process a file upload in memory 
    byte[] data = item.get(); 
    //...省略步驟 
    //如果這個(gè)文件真的很大,你可能會(huì)希望向用戶報(bào)告到底傳了多少到服務(wù)端,讓用戶了解上傳的過(guò)程 
    //Create a progress listener 
    ProgressListener progressListener = new ProgressListener(){ 
      public void update(long pBytesRead, long pContentLength, int pItems) { 
        System.out.println("We are currently reading item " + pItems); 
        if (pContentLength == -1) { 
          System.out.println("So far, " + pBytesRead + " bytes have been read."); 
        } else { 
          System.out.println("So far, " + pBytesRead + " of " + pContentLength 
                   + " bytes have been read."); 
        } 
      } 
    }; 
    upload.setProgressListener(progressListener);

11、HttpClient

 基于HttpCore實(shí) 現(xiàn)的一個(gè)HTTP/1.1兼容的HTTP客戶端,它提供了一系列可重用的客戶端身份驗(yàn)證、HTTP狀態(tài)保持、HTTP連接管理module。

//GET方法 
  import java.io.IOException; 
  import org.apache.commons.httpclient.*; 
  import org.apache.commons.httpclient.methods.GetMethod; 
  import org.apache.commons.httpclient.params.HttpMethodParams; 
   
  public class GetSample{ 
    public static void main(String[] args) { 
      // 構(gòu)造HttpClient的實(shí)例 
      HttpClient httpClient = new HttpClient(); 
      // 創(chuàng)建GET方法的實(shí)例 
      GetMethod getMethod = new GetMethod("http://www.ibm.com"); 
      // 使用系統(tǒng)提供的默認(rèn)的恢復(fù)策略 
      getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
          new DefaultHttpMethodRetryHandler()); 
      try { 
        // 執(zhí)行g(shù)etMethod 
        int statusCode = httpClient.executeMethod(getMethod); 
        if (statusCode != HttpStatus.SC_OK) { 
          System.err.println("Method failed: " 
              + getMethod.getStatusLine()); 
        } 
        // 讀取內(nèi)容 
        byte[] responseBody = getMethod.getResponseBody(); 
        // 處理內(nèi)容 
        System.out.println(new String(responseBody)); 
      } catch (HttpException e) { 
        // 發(fā)生致命的異常,可能是協(xié)議不對(duì)或者返回的內(nèi)容有問(wèn)題 
        System.out.println("Please check your provided http address!"); 
        e.printStackTrace(); 
      } catch (IOException e) { 
        // 發(fā)生網(wǎng)絡(luò)異常 
        e.printStackTrace(); 
      } finally { 
        // 釋放連接 
        getMethod.releaseConnection(); 
      } 
    } 
  } 
   
  //POST方法 
  import java.io.IOException; 
  import org.apache.commons.httpclient.*; 
  import org.apache.commons.httpclient.methods.PostMethod; 
  import org.apache.commons.httpclient.params.HttpMethodParams; 
   
  public class PostSample{ 
    public static void main(String[] args) { 
      // 構(gòu)造HttpClient的實(shí)例 
      HttpClient httpClient = new HttpClient(); 
      // 創(chuàng)建POST方法的實(shí)例 
      String url = "http://www.oracle.com/"; 
      PostMethod postMethod = new PostMethod(url); 
      // 填入各個(gè)表單域的值 
      NameValuePair[] data = { new NameValuePair("id", "youUserName"), 
      new NameValuePair("passwd", "yourPwd") }; 
      // 將表單的值放入postMethod中 
      postMethod.setRequestBody(data); 
      // 執(zhí)行postMethod 
      int statusCode = httpClient.executeMethod(postMethod); 
      // HttpClient對(duì)于要求接受后繼服務(wù)的請(qǐng)求,象POST和PUT等不能自動(dòng)處理轉(zhuǎn)發(fā) 
      // 301或者302 
      if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||  
      statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { 
        // 從頭中取出轉(zhuǎn)向的地址 
        Header locationHeader = postMethod.getResponseHeader("location"); 
        String location = null; 
        if (locationHeader != null) { 
         location = locationHeader.getValue(); 
         System.out.println("The page was redirected to:" + location); 
        } else { 
         System.err.println("Location field value is null."); 
        } 
        return; 
      } 
    } 
  }

12、IO 

對(duì)java.io的擴(kuò)展 操作文件非常方便。

//1.讀取Stream 
   
  //標(biāo)準(zhǔn)代碼: 
  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); 
  } 
   
  //2.讀取文件 
  File file = new File("/commons/io/project.properties"); 
  List lines = FileUtils.readLines(file, "UTF-8"); 
  //3.察看剩余空間 
  long freeSpace = FileSystemUtils.freeSpace("C:/");

13、Lang 

主要是一些公共的工具集合,比如對(duì)字符、數(shù)組的操作等等。

// 1 合并兩個(gè)數(shù)組: org.apache.commons.lang. ArrayUtils 
    // 有時(shí)我們需要將兩個(gè)數(shù)組合并為一個(gè)數(shù)組,用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()); 
   
    } 
    //2 截取從from開(kāi)始字符串 
    StringUtils.substringAfter("SELECT * FROM PERSON ", "from"); 
    //3 判斷該字符串是不是為數(shù)字(0~9)組成,如果是,返回true 但該方法不識(shí)別有小數(shù)點(diǎn)和 請(qǐng)注意。 
    StringUtils.isNumeric("454534"); //返回true 
    //4.取得類名 
      System.out.println(ClassUtils.getShortClassName(Test.class)); 
      //取得其包名 
      System.out.println(ClassUtils.getPackageName(Test.class)); 
      
      //5.NumberUtils 
      System.out.println(NumberUtils.stringToInt("6")); 
      //6.五位的隨機(jī)字母和數(shù)字 
      System.out.println(RandomStringUtils.randomAlphanumeric(5)); 
      //7.StringEscapeUtils 
      System.out.println(StringEscapeUtils.escapeHtml("<html>")); 
      //輸出結(jié)果為&lt;html&gt; 
      System.out.println(StringEscapeUtils.escapeJava("String")); 
      
      //8.StringUtils,判斷是否是空格字符 
      System.out.println(StringUtils.isBlank("  ")); 
      //將數(shù)組中的內(nèi)容以,分隔 
      System.out.println(StringUtils.join(test,",")); 
      //在右邊加下字符,使之總長(zhǎng)度為6 
      System.out.println(StringUtils.rightPad("abc", 6, 'T')); 
      //首字母大寫(xiě) 
      System.out.println(StringUtils.capitalize("abc")); 
      //Deletes all whitespaces from a String 刪除所有空格 
      System.out.println( StringUtils.deleteWhitespace("  ab c ")); 
      //判斷是否包含這個(gè)字符 
      System.out.println( StringUtils.contains("abc", "ba")); 
      //表示左邊兩個(gè)字符 
      System.out.println( StringUtils.left("abc", 2)); 
      System.out.println(NumberUtils.stringToInt("33"));

14、Logging 

提供的是一個(gè)Java 的日志接口,同時(shí)兼顧輕量級(jí)和不依賴于具體的日志實(shí)現(xiàn)工具。

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()); 
     } 
   
    }

15、Validator 

通用驗(yàn)證系統(tǒng),該組件提供了客戶端和服務(wù)器端的數(shù)據(jù)驗(yàn)證框架。 

 驗(yàn)證日期

// 獲取日期驗(yàn)證 
     DateValidator validator = DateValidator.getInstance(); 
   
     // 驗(yàn)證/轉(zhuǎn)換日期 
     Date fooDate = validator.validate(fooString, "dd/MM/yyyy"); 
     if (fooDate == null) { 
       // 錯(cuò)誤 不是日期 
       return; 
     }

表達(dá)式驗(yàn)證

// 設(shè)置參數(shù) 
     boolean caseSensitive = false; 
     String regex1  = "^([A-Z]*)(?:\\-)([A-Z]*)*$" 
     String regex2  = "^([A-Z]*)$"; 
     String[] regexs = new String[] {regex1, regex1}; 
   
     // 創(chuàng)建驗(yàn)證 
     RegexValidator validator = new RegexValidator(regexs, caseSensitive); 
   
     // 驗(yàn)證返回boolean 
     boolean valid = validator.isValid("abc-def"); 
   
     // 驗(yàn)證返回字符串 
     String result = validator.validate("abc-def"); 
   
     // 驗(yàn)證返回?cái)?shù)組 
     String[] groups = validator.match("abc-def");

配置文件中使用驗(yàn)證

<form-validation> 
    <global> 
      <validator name="required" 
       classname="org.apache.commons.validator.TestValidator" 
       method="validateRequired" 
       methodParams="java.lang.Object, org.apache.commons.validator.Field"/> 
    </global> 
    <formset> 
    </formset> 
  </form-validation> 
   
  添加姓名驗(yàn)證. 
   
  <form-validation> 
    <global> 
      <validator name="required" 
       classname="org.apache.commons.validator.TestValidator" 
       method="validateRequired" 
       methodParams="java.lang.Object, org.apache.commons.validator.Field"/> 
    </global> 
    <formset> 
      <form name="nameForm"> 
       <field property="firstName" depends="required"> 
         <arg0 key="nameForm.firstname.displayname"/> 
       </field> 
       <field property="lastName" depends="required"> 
         <arg0 key="nameForm.lastname.displayname"/> 
       </field> 
      </form> 
    </formset> 
  </form-validation>

驗(yàn)證類

Excerpts from org.apache.commons.validator.RequiredNameTest 
//加載驗(yàn)證配置文件 
InputStream in = this.getClass().getResourceAsStream("validator-name-required.xml"); 
 
ValidatorResources resources = new ValidatorResources(in); 
//這個(gè)是自己創(chuàng)建的bean 我這里省略了 
Name name = new Name(); 
 
Validator validator = new Validator(resources, "nameForm"); 
//設(shè)置參數(shù) 
validator.setParameter(Validator.BEAN_PARAM, name); 
 
 
Map results = null; 
//驗(yàn)證 
results = validator.validate(); 
 
if (results.get("firstName") == null) { 
  //驗(yàn)證成功 
} else { 
  //有錯(cuò)誤   int errors = ((Integer)results.get("firstName")).intValue(); 
}

至此我們?yōu)榇蠹液?jiǎn)單介紹了Java常用類庫(kù)Apache Commons工具類說(shuō)明及使用實(shí)例更多Java常用類庫(kù)請(qǐng)查看下面的相關(guān)鏈接

相關(guān)文章

  • Springboot集成Quartz實(shí)現(xiàn)定時(shí)任務(wù)代碼實(shí)例

    Springboot集成Quartz實(shí)現(xiàn)定時(shí)任務(wù)代碼實(shí)例

    這篇文章主要介紹了Springboot集成Quartz實(shí)現(xiàn)定時(shí)任務(wù)代碼實(shí)例,任務(wù)是有可能并發(fā)執(zhí)行的,若Scheduler直接使用Job,就會(huì)存在對(duì)同一個(gè)Job實(shí)例并發(fā)訪問(wèn)的問(wèn)題,而JobDetail?&?Job方式,Scheduler都會(huì)根據(jù)JobDetail創(chuàng)建一個(gè)新的Job實(shí)例,這樣就可以規(guī)避并發(fā)訪問(wèn)問(wèn)題
    2023-09-09
  • redis發(fā)布訂閱Java代碼實(shí)現(xiàn)過(guò)程解析

    redis發(fā)布訂閱Java代碼實(shí)現(xiàn)過(guò)程解析

    這篇文章主要介紹了redis發(fā)布訂閱Java代碼實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • Java讀取.properties配置文件方法示例

    Java讀取.properties配置文件方法示例

    這篇文章主要介紹了Java讀取.properties配置文件,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • Java新API的時(shí)間格式化

    Java新API的時(shí)間格式化

    這篇文章主要介紹了Java新API的時(shí)間格式化,新的時(shí)間API的時(shí)間格式化由java.time.format.DateTimeFormatter負(fù)責(zé),更多相關(guān)資料需要的小伙伴可以參考一下
    2022-05-05
  • java實(shí)現(xiàn)簡(jiǎn)單計(jì)算器功能

    java實(shí)現(xiàn)簡(jiǎn)單計(jì)算器功能

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡(jiǎn)單計(jì)算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-12-12
  • springboot 整合 nacos 配置實(shí)現(xiàn)多個(gè)環(huán)境不同配置

    springboot 整合 nacos 配置實(shí)現(xiàn)多個(gè)環(huán)境不同配置

    本文介紹了Nacos配置中心的優(yōu)勢(shì),包括與Apollo的性能對(duì)比,Nacos服務(wù)端的安裝與配置,以及如何在SpringBoot項(xiàng)目中集成Nacos進(jìn)行多環(huán)境配置,提供了詳細(xì)的步驟,包括下載、安裝、配置中心的創(chuàng)建和項(xiàng)目集成,旨在幫助開(kāi)發(fā)者更好地使用Nacos進(jìn)行項(xiàng)目配置管理
    2024-09-09
  • Android 應(yīng)用按返回鍵退向后臺(tái)運(yùn)行實(shí)例代碼

    Android 應(yīng)用按返回鍵退向后臺(tái)運(yùn)行實(shí)例代碼

    這篇文章主要介紹了Android 應(yīng)用按返回鍵退向后臺(tái)運(yùn)行實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • 詳解Spring Boot 2.0.2+Ajax解決跨域請(qǐng)求的問(wèn)題

    詳解Spring Boot 2.0.2+Ajax解決跨域請(qǐng)求的問(wèn)題

    這篇文章主要介紹了詳解Spring Boot 2.0.2+Ajax解決跨域請(qǐng)求的問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • gRPC與SpringBoot整合思路和步驟

    gRPC與SpringBoot整合思路和步驟

    在現(xiàn)代微服務(wù)架構(gòu)中,gRPC已經(jīng)成為了非常受歡迎的通信協(xié)議,與SpringBoot整合,它為開(kāi)發(fā)者提供了簡(jiǎn)潔、高效構(gòu)建分布式應(yīng)用,在整合gRPC與SpringBoot時(shí),將gRPC的服務(wù)端和客戶端分別封裝到SpringBoot的應(yīng)用中,感興趣的朋友一起看看吧
    2023-08-08
  • NoHttpResponseException異常解決優(yōu)化HttpClient配置以避免連接問(wèn)題

    NoHttpResponseException異常解決優(yōu)化HttpClient配置以避免連接問(wèn)題

    這篇文章主要為大家介紹了NoHttpResponseException異常解決,優(yōu)化HttpClient配置以避免連接問(wèn)題詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-10-10

最新評(píng)論