看文時發現老鐵一句“不了解Apache Commons的java程式員不算java程式員”,瞬間紮鐵了。趕緊搜了一下,發現這裡面有些類是用過的,隻是沒有對它有個總體的印象
看了部分相關使用博文中互相複制粘貼失了原有的格式。本文主要目的為整理常用類,成為自用的一個快速搜尋清單。
最近的一篇關于這個工具包的博文是《apache-commons家族的八兄弟》
主要列出了
元件 | 功能介紹 |
beanUtils | 提供了對于JavaBean進行各種操作,克隆對象,屬性等等. |
codec | 處理常用的編碼方法的工具類包 例如DES、SHA1、MD5、Base64等. |
collections | java集合架構操作. |
configuration | 一個java應用程式的配置管理類庫. |
io | io工具的封裝. |
lang | Java基本對象方法的工具類包 如:StringUtils,ArrayUtils等等. |
logging | 提供的是一個Java 的日志接口. |
net | 提供了用戶端和伺服器端的資料驗證架構. |
另一篇博文是https://blog.csdn.net/zs064811/article/details/51601912
元件 | 功能介紹 |
BeanUtils | 提供了對于JavaBean進行各種操作,克隆對象,屬性等等. |
Betwixt | XML與Java對象之間互相轉換. |
Codec | 處理常用的編碼方法的工具類包 例如DES、SHA1、MD5、Base64等. |
Collections | java集合架構操作. |
Compress | java提供檔案打包 壓縮類庫. |
Configuration | 一個java應用程式的配置管理類庫. |
DBCP | 提供資料庫連接配接池服務. |
DbUtils | 提供對jdbc 的操作封裝來簡化資料查詢和記錄讀取操作. |
java發送郵件 對javamail的封裝. | |
FileUpload | 提供檔案上傳功能. |
HttpClien | 提供HTTP用戶端與伺服器的各種通訊操作. 現在已改成HttpComponents |
IO | io工具的封裝. |
Lang | Java基本對象方法的工具類包 如:StringUtils,ArrayUtils等等. |
Logging | 提供的是一個Java 的日志接口. |
Validator | 提供了用戶端和伺服器端的資料驗證架構. |
1.BeanUtils
文章基本都把它列為最重要的部分。應用及其廣泛。
主要用來組裝對象,包含設定、指派、克隆的一系列操作。隻有你想不到,沒有他沒寫到。
這裡我注意了一點,和我用過的反射機制一樣,可以通過PropertyUtils擷取私有屬性的值。
另外有文章說Struts的創始人Craig McClanahan是BeanUtils的作者之一。難怪用的時候讓我不停地想起曾經折騰過得的配置javabean。
2.Codec
第二個講的是Codec,本質上就是編碼解碼,加密解密,encode,decode,方法名稱都和以前用過得很接近。
廣泛地使用Base64, Hex, MD5,Phonetic and URLs
3.Collections
這個包也是個重量級的工具了,看了一個不錯的分類方式:
- 容器類:如Collection、List、Map等,用于存放對象和進行簡單操作的;
- 操作類:如Collections、Arrays等,用于對容器類的執行個體進行相對複雜操作如排序等;
- 輔助類:如Iterator、Comparator等,用于輔助操作類以及外部調用代碼實作對容器類的操作,所謂輔助,概括而通俗的來講,就是這些類提供一種算法,你給它一個對象或者一組對象,或者僅僅是按一定的規則調用它,它給你一個運算後的答案,幫助你正确處理容器對象。比如Iterator會告訴你容器中下一個對象有沒有、是什麼,而Comparator将對象大小/先後次序的算法邏輯獨立出來。
=未完待續=
##4.Configuration ##
用來處理配置檔案的,可以适配多種存儲方式
- Properties files
- XML documents
- Property list files (.plist)
- JNDI
- JDBC Datasource
- System properties
- Applet parameters
-
Servlet parameters
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”);
5.IO
正常的緩沖流套輸入輸出流
//标準代碼:
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:/");
6.Lang
主要是一些公共的工具集合,比如對字元、數組的操作等等。
// 1 合并兩個數組: org.apache.commons.lang. ArrayUtils
// 有時我們需要将兩個數組合并為一個數組,用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開始字元串
StringUtils.substringAfter("SELECT * FROM PERSON ", “from”);
//3 判斷該字元串是不是為數字(0~9)組成,如果是,傳回true 但該方法不識别有小數點和 請注意
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.五位的随機字母和數字
System.out.println(RandomStringUtils.randomAlphanumeric(5));
//7.StringEscapeUtils
System.out.println(StringEscapeUtils.escapeHtml("<html>"));
//輸出結果為<html>
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"));
7.logging
其實沒什麼必要,業界多半用log4j logback等
log.error(“ERROR”);
log.debug(“DEBUG”);
log.warn(“WARN”);
log.info(“INFO”);
log.trace(“TRACE”);
8.net
Apache Commons Net™庫實作了許多基本Internet協定的用戶端。該庫的目的是提供基本協定通路,而不是更進階别的抽象。是以,一些設計違反了面向對象的設計原則。我們的理念是盡可能使協定的全局功能可通路(例如,TFTP發送檔案和接收檔案),但也提供對适用的基本協定的通路,以便程式員可以建構自己的自定義實作(例如,TFTP)資料包類和TFTP資料包的發送和接收方法都是公開的)。
支援協定:
-FTP / FTPS
-FTP over HTTP(實驗性)
-NNTP 網絡新聞傳輸協定
-SMTP(S)簡單郵件傳輸協定
-POP3(S)郵件協定版本3
-IMAP(S)郵件通路協定
-telnet 遠端登入
-TFTP 簡單檔案傳輸協定
-finger
-whois 用來查詢域名的IP以及所有者等資訊的傳輸協定
-REXEC / RCMD /遠端登入
-daytime(rdate)和白天
-echo
-discard
-NTP / SNTP 網絡時間協定
- FTP/FTPS
- FTP over HTTP (experimental)
- NNTP
- SMTP(S)
- POP3(S)
- IMAP(S)
- Telnet
- TFTP
- Finger
- Whois
- rexec/rcmd/rlogin
- Time (rdate) and Daytime
- Echo
- Discard
- NTP/SNTP
其他.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();
其他.FileUpload
//官方示例:
//* 檢查請求是否含有上傳檔案
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//現在我們得到了items的清單
//如果你的應用近于最簡單的情況,上面的處理就夠了。但我們有時候還是需要更多的控制。
//下面提供了幾種控制選擇:
// 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);
// 設定最大上傳大小
upload.setSizeMax(yourMaxRequestSize);
// 解析所有請求
List /* FileItem */ items = upload.parseRequest(request);
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory(
yourMaxMemorySize, yourTempDirectory);
//一旦解析完成,你需要進一步處理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);
}
}
//區分資料是否為簡單的表單資料,如果是簡單的資料:
// 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();
//...省略步驟
}
//對于這些item,我們通常要把它們寫入檔案,或轉為一個流
// Process a file upload
if (writeToFile) {
File uploadedFile = new File(...);
item.write(uploadedFile);
} else {
InputStream uploadedStream = item.getInputStream();
//...省略步驟
uploadedStream.close();
}
//或轉為位元組數組儲存在記憶體中:
// Process a file upload in memory
byte[] data = item.get();
//...省略步驟
//如果這個檔案真的很大,你可能會希望向使用者報告到底傳了多少到服務端,讓使用者了解上傳的過程
//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);
其他lang.math
注意與math包的區分
在Jakarta Commons中,專門處理數學計算的類分别可以在兩個地方找到:一是Commons Lang的org.apache.commons.lang.math包中,二是在Commons Math這個單獨的子項目中。由于後者主要是處理複數、矩陣等。
org.apache.commons.lang.math包中共有10個類,這些類可以歸納成四組:
1.處理分數的 Fraction 類;
2.處理數值的 NumberUtils 類;
3.處理數值範圍的 Range 、 NumberRange 、 IntRange 、 LongRange 、 FloatRange 、 DoubleRange 類;
4.處理随機數的 JVMRandom 和 RandomUtils 類。