Apache Commons contains many open source tools that are used to solve problems commonly encountered in daily programming and reduce duplication of work. I have selected some commonly used projects for a brief introduction. The article uses a lot of ready-made things on the Internet, I just made a summary.
1. Commons BeanUtils
http://jakarta.apache.org/commons/beanutils/index.html
Description: A tool set for Bean. Since Beans are often composed of a bunch of get and set, BeanUtils also performs some packaging on this basis.
Usage examples: There are many functions, which are described in detail on the website. One of the more commonly used functions is Bean Copy, which is to copy the properties of a bean. It will be used if you are developing a layered architecture, such as copying data from PO (Persistent Object) to VO (Value Object).
The traditional method is as follows:
//得到TeacherForm TeacherForm teacherForm=(TeacherForm)form; //构造Teacher对象 Teacher teacher=new Teacher(); //赋值 teacher.setName(teacherForm.getName()); teacher.setAge(teacherForm.getAge()); teacher.setGender(teacherForm.getGender()); teacher.setMajor(teacherForm.getMajor()); teacher.setDepartment(teacherForm.getDepartment()); //持久化Teacher对象到数据库 HibernateDAO= ; HibernateDAO.save(teacher);
After using BeanUtils, the code has been greatly improved, as shown below:
//得到TeacherForm TeacherForm teacherForm=(TeacherForm)form; //构造Teacher对象 Teacher teacher=new Teacher(); //赋值 BeanUtils.copyProperties(teacher,teacherForm); //持久化Teacher对象到数据库 HibernateDAO= ; HibernateDAO.save(teacher);
2. Commons CLI
http://jakarta.apache.org/commons/cli/index.html
Description: This is a tool for processing commands. For example, the string[] input by the main method needs to be parsed. You can pre-define the parameter rules and then call the CLI to parse them.
Usage example:
// 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
}3. Commons Codec
http://jakarta.apache.org/commons/codec/index.html
Instructions : This tool is used for encoding and decoding, including Base64, URL, Soundx and more. People who use this tool should know these very well, so I won’t introduce them in detail.
4. Commons Collections
http://jakarta.apache.org/commons/collections/
Note: You can think of this tool as an extension of java.util.
Usage example: Give a simple example
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"5. Commons Configuration
http://jakarta.apache.org/commons/configuration/
Description: This tool is used to help process configuration files and supports many storage methods
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
Usage example: Give a simple example of Properties
# usergui.properties, definining the GUI,
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");
Commons DBCPhttp://jakarta.apache.org/commons/dbcp/
Description: Database Connection pool, this is what Tomcat uses. I don’t need to say more. If you want to use it, go to the website and read the instructions.
6. Commons DbUtils
http://jakarta.apache.org/commons/dbutils/
Note: When I used to write database programs, I often made a separate package for database operations. DbUtils is such a tool, so you don’t have to repeat this kind of work in future development. It is worth mentioning that this tool is not the popular OR-Mapping tool (such as Hibernate), but only simplifies database operations, such as
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");7. Commons FileUpload
http:/ /jakarta.apache.org/commons/fileupload/
Explanation: How to use the jsp file upload function?
Usage example:
// 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);
}
}8. Commons HttpClient
http://jakarta.apache.org/commons/httpclient/
Description: This tool It is convenient to access the website through programming.
Usage example: the simplest Get operation
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();9. Commons IO
http://jakarta.apache.org/commons/io/
Description: It can be regarded as an extension of java.io. I think it is very convenient to use.
Usage examples:
1. Read Stream
standard code:
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();
}Use IOUtils
InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
try {
System.out.println( IOUtils.toString( in ) );
} finally {
IOUtils.closeQuietly(in);
}2. Read file
File file = new File("/commons/io/project.properties");
List lines = FileUtils.readLines(file, "UTF-8");3. Check the remaining space
long freeSpace = FileSystemUtils.freeSpace("C:/");10. Commons JXPath
http://jakarta.apache.org/commons/jxpath/
Explanation: You know Xpath, then JXpath is Xpath based on Java objects, that is, using Xpath to query Java objects. This thing is still very imaginative.
Usage example:
Address address = (Address)JXPathContext.newContext(vendor).
getValue("locations[address/zipCode='90210']/address");
上述代码等同于
Address address = null;
Collection locations = vendor.getLocations();
Iterator it = locations.iterator();
while (it.hasNext()){
Location location = (Location)it.next();
String zipCode = location.getAddress().getZipCode();
if (zipCode.equals("90210")){
address = location.getAddress();
break;
}
}11. Commons Lang
http://jakarta.apache.org/commons/lang/
Instructions: This The toolkit can be viewed as an extension to java.lang. Provides tool classes such as StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils, etc.
12. Commons Logging
http://jakarta.apache.org/commons/logging/
Explanation: Do you know Log4j?
13. Commons Math
http://jakarta.apache.org/commons/math/
Note: You should know what this package is used for by looking at the name. The functions provided by this package are somewhat duplicated by Commons Lang, but this package is more focused on making mathematical tools and has more powerful functions.
Fourteen. Commons Net
http://jakarta.apache.org/commons/net/
Description: This package is still very practical and encapsulates many network protocols.
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
Usage example:
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);以上就是java-类库-Apache Commons补充的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PMThe article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.
How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PMThe article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.
How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PMThe article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra
How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PMThe article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]
How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PMJava's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.






