Commons CLI http://jakarta.apache.org/commons/cli/index.html 说明:这是一个处理命令的工具。比如main方法输入的string[]需要解析。你可以预先定义好参数的规则,然后就可以调用CLI来解析。 使用示例: // create Options object Options options = new Options(); // add t option, option is the command parameter, false indicates that // this parameter is not required. options.addOption(“t”, false, “display current time”); options.addOption("c", true, "country code"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse( options, args); if(cmd.hasOption("t")) { // print the date and time } else { // print the date } // get c option value String countryCode = cmd.getOptionValue("c");
if(countryCode == null) { // print default date } else { // print date for country specified by countryCode }
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");
Commons DBCP http://jakarta.apache.org/commons/dbcp/ 说明:Database Connection pool, Tomcat就是用的这个,不用我多说了吧,要用的自己去网站上看说明。
Commons DbUtils http://jakarta.apache.org/commons/dbutils/ 说明:我以前在写数据库程序的时候,往往把数据库操作单独做一个包。DbUtils就是这样一个工具,以后开发不用再重复这样的工作了。值得一体的是,这个工具并不是现在流行的OR-Mapping工具(比如Hibernate),只是简化数据库操作,比如 QueryRunner run = new QueryRunner(dataSource); // Execute the query and get the results back from the handler Object[] result = (Object[]) run.query( "Select * FROM Person Where name=?", "John Doe");
Commons FileUpload http://jakarta.apache.org/commons/fileupload/ 说明:jsp的上传文件功能怎么做呢? 使用示例: // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next();
if (item.isFormField()) { processFormField(item); } else { processUploadedFile(item); } }
Commons HttpClient http://jakarta.apache.org/commons/httpclient/ 说明:这个工具可以方便通过编程的方式去访问网站。 使用示例:最简单的Get操作 GetMethod get = new GetMethod("http://jakarta.apache.org"); // execute method and handle any error responses. ... InputStream in = get.getResponseBodyAsStream(); // Process the data from the input stream. get.releaseConnection();
Commons IO http://jakarta.apache.org/commons/io/ 说明:可以看成是java.io的扩展,我觉得用起来非常方便。 使用示例: 1.读取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); }
2.读取文件 File file = new File("/commons/io/project.properties"); List lines = FileUtils.readLines(file, "UTF-8");
3.察看剩余空间 long freeSpace = FileSystemUtils.freeSpace("C:/");
Commons Math http://jakarta.apache.org/commons/math/ 说明:看名字你就应该知道这个包是用来干嘛的了吧。这个包提供的功能有些和Commons Lang重复了,但是这个包更专注于做数学工具,功能更强大。
Commons Net http://jakarta.apache.org/commons/net/ 说明:这个包还是很实用的,封装了很多网络协议。 1. FTP 2. NNTP 3. SMTP 4. POP3 5. Telnet 6. TFTP 7. Finger 8. Whois 9. rexec/rcmd/rlogin 10. Time (rdate) and Daytime 11. Echo 12. Discard 13. NTP/SNTP 使用示例: TelnetClient telnet = new TelnetClient(); telnet.connect( "192.168.1.99", 23 ); InputStream in = telnet.getInputStream(); PrintStream out = new PrintStream( telnet.getOutputStream() ); ... telnet.close();
Commons Validator http://jakarta.apache.org/commons/validator/ 说明:用来帮助进行验证的工具。比如验证Email字符串,日期字符串等是否合法。 使用示例: // Get the Date validator DateValidator validator = DateValidator.getInstance(); // Validate/Convert the date Date fooDate = validator.validate(fooString, "dd/MM/yyyy"); if (fooDate == null) { // error...not a valid date return; }
Commons Virtual File System http://jakarta.apache.org/commons/vfs/ 说明:提供对各种资源的访问接口。支持的资源类型包括 1. CIFS 2. FTP 3. Local Files 4. HTTP and HTTPS 5. SFTP 6. Temporary Files 7. WebDAV 8. Zip, Jar and Tar (uncompressed, tgz or tbz2) 9. gzip and bzip2 10. res 11. ram 这个包的功能很强大,极大的简化了程序对资源的访问。 使用示例: 从jar中读取文件 // Locate the Jar file FileSystemManager fsManager = VFS.getManager(); FileObject jarFile = fsManager.resolveFile( "jar:lib/aJarFile.jar" );
// List the children of the Jar file FileObject[] children = jarFile.getChildren(); System.out.println( "Children of " + jarFile.getName().getURI() ); for ( int i = 0; i < children.length; i++ ) { System.out.println( children[ i ].getName().getBaseName() ); } 从smb读取文件 StaticUserAuthenticator auth = new StaticUserAuthenticator("username", "password", null); FileSystemOptions opts = new FileSystemOptions(); DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth); FileObject fo = VFS.getManager().resolveFile("smb://host/anyshare/dir", opts);
1. // create Options object 2. Options options = new Options(); 3. // add t option, option is the command parameter, false indicates that 4. // this parameter is not required. 5. 6. options.addOption(“t”, false, “display current time”); 7. options.addOption("c", true, "country code"); 8. 9. CommandLineParser parser = new PosixParser(); 10. CommandLine cmd = parser.parse( options, args); 11. 12. if(cmd.hasOption("t")) { 13. // print the date and time 14. }else { 15. // print the date 16. } 17. 18. // get c option value 19. String countryCode = cmd.getOptionValue("c"); 20. 21. if(countryCode == null) { 22. // print default date 23. }else { 24. // print date for country specified by countryCode 25. }
// create Options object Options options = new Options(); // add t option, option is the command parameter, false indicates that // this parameter is not required. options.addOption(“t”, false, “display current time”); options.addOption("c", true, "country code"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse( options, args); if(cmd.hasOption("t")) { // print the date and time }else { // print the date } // get c option value String countryCode = cmd.getOptionValue("c"); if(countryCode == null) { // print default date }else { // print date for country specified by countryCode }
1. QueryRunner run = new QueryRunner(dataSource); 2. 3. // Execute the query and get the results back from the handler 4. Object[] result = (Object[]) run.query("SELECT * FROM Person WHERE name=?", "John Doe");
QueryRunner run = new QueryRunner(dataSource); // Execute the query and get the results back from the handler Object[] result = (Object[]) run.query("SELECT * FROM Person WHERE name=?", "John Doe");
八、Commons FileUpload
http://jakarta.apache.org/commons/fileupload/
说明:jsp的上传文件功能怎么做呢?
使用示例:
Java代码 复制代码
1. // Create a factory for disk-based file items 2. FileItemFactory factory = new DiskFileItemFactory(); 3. // Create a new file upload handler 4. ServletFileUpload upload = new ServletFileUpload(factory); 5. 6. // Parse the request 7. List /* FileItem */ items = upload.parseRequest(request); 8. // Process the uploaded items 9. Iterator iter = items.iterator(); 10. while (iter.hasNext()) { 11. FileItem item = (FileItem) iter.next(); 12. if (item.isFormField()) { 13. processFormField(item); 14. } else { 15. processUploadedFile(item); 16. } 17. }
// Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { processFormField(item); } else { processUploadedFile(item); } }
九、Commons HttpClient
http://jakarta.apache.org/commons/httpclient/
说明:这个工具可以方便通过编程的方式去访问网站。
使用示例:最简单的Get操作
Java代码 复制代码
1. GetMethod get = new GetMethod("http://jakarta.apache.org"); 2. 3. // execute method and handle any error responses. 4. 5. ... 6. 7. InputStream in = get.getResponseBodyAsStream(); 8. // Process the data from the input stream. 9. get.releaseConnection();
GetMethod get = new GetMethod("http://jakarta.apache.org"); // execute method and handle any error responses. ... InputStream in = get.getResponseBodyAsStream(); // Process the data from the input stream. get.releaseConnection();
十、Commons IO
http://jakarta.apache.org/commons/io/
说明:可以看成是java.io的扩展,我觉得用起来非常方便。
使用示例:
1.读取Stream
标准代码:
Java代码 复制代码
1. InputStream in = new URL( "http://jakarta.apache.org" ).openStream(); 2. try { 3. InputStreamReader inR = new InputStreamReader( in ); 4. BufferedReader buf = new BufferedReader( inR ); 5. String line; 6. while ( ( line = buf.readLine() ) != null ) { 7. System.out.println( line ); 8. } 9. } finally { 10. in.close(); 11. }
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
Java代码 复制代码
1. InputStream in = new URL( "http://jakarta.apache.org" ).openStream(); 2. try { 3. System.out.println( IOUtils.toString( in ) ); 4. } finally { 5. IOUtils.closeQuietly(in); 6. }
InputStream in = new URL( "http://jakarta.apache.org" ).openStream(); try { System.out.println( IOUtils.toString( in ) ); } finally { IOUtils.closeQuietly(in); }
2.读取文件
Java代码 复制代码
1. File file = new File("/commons/io/project.properties"); 2. List lines = FileUtils.readLines(file, "UTF-8");
File file = new File("/commons/io/project.properties"); List lines = FileUtils.readLines(file, "UTF-8");
3.察看剩余空间
Java代码 复制代码
1. long freeSpace = FileSystemUtils.freeSpace("C:/");
long freeSpace = FileSystemUtils.freeSpace("C:/");
1. TelnetClient telnet = new TelnetClient(); 2. telnet.connect( "192.168.1.99", 23 ); 3. InputStream in = telnet.getInputStream(); 4. PrintStream out = new PrintStream( telnet.getOutputStream() ); 5. ... 6. telnet.close();
TelnetClient telnet = new TelnetClient(); telnet.connect( "192.168.1.99", 23 ); InputStream in = telnet.getInputStream(); PrintStream out = new PrintStream( telnet.getOutputStream() ); ... telnet.close();
十六、Commons Validator
http://jakarta.apache.org/commons/validator/
说明:用来帮助进行验证的工具。比如验证Email字符串,日期字符串等是否合法。
使用示例:
Java代码 复制代码
1. // Get the Date validator 2. DateValidator validator = DateValidator.getInstance(); 3. // Validate/Convert the date 4. Date fooDate = validator.validate(fooString, "dd/MM/yyyy"); 5. if (fooDate == null) { 6. // error...not a valid date 7. return; 8. }
// Get the Date validator DateValidator validator = DateValidator.getInstance(); // Validate/Convert the date Date fooDate = validator.validate(fooString, "dd/MM/yyyy"); if (fooDate == null) { // error...not a valid date return; }
十七、Commons Virtual File System
http://jakarta.apache.org/commons/vfs/
说明:提供对各种资源的访问接口。支持的资源类型包括
* 1. CIFS * 2. FTP * 3. Local Files * 4. HTTP and HTTPS * 5. SFTP * 6. Temporary Files * 7. WebDAV * 8. Zip, Jar and Tar (uncompressed, tgz or tbz2) * 9. gzip and bzip2 * 10. res * 11. ram
这个包的功能很强大,极大的简化了程序对资源的访问。
使用示例:
从jar中读取文件
Java代码 复制代码
1. // Locate the Jar file 2. FileSystemManager fsManager = VFS.getManager(); 3. FileObject jarFile = fsManager.resolveFile( "jar:lib/aJarFile.jar" ); 4. 5. // List the children of the Jar file 6. FileObject[] children = jarFile.getChildren(); 7. System.out.println( "Children of " + jarFile.getName().getURI() ); 8. for ( int i = 0; i < children.length; i++ ){ 9. System.out.println( children[ i ].getName().getBaseName() ); 10. }
// Locate the Jar file FileSystemManager fsManager = VFS.getManager(); FileObject jarFile = fsManager.resolveFile( "jar:lib/aJarFile.jar" ); // List the children of the Jar file FileObject[] children = jarFile.getChildren(); System.out.println( "Children of " + jarFile.getName().getURI() ); for ( int i = 0; i < children.length; i++ ){ System.out.println( children[ i ].getName().getBaseName() ); }
* 1. makeObject is called whenever a new instance is needed. * 2. activateObject is invoked on every instance before it is returned from the pool. * 3. passivateObject is invoked on every instance when it is returned to the pool. * 4. destroyObject is invoked on every instance when it is being "dropped" from the pool (whether due to the response from validateObject, or for reasons specific to the pool implementation.) * 5. validateObject is invoked in an implementation-specific fashion to determine if an instance is still valid to be returned by the pool. It will only be invoked on an "activated" instance.