Home > Java > javaTutorial > body text

java-class library-Apache Commons supplement

黄舟
Release: 2017-01-19 13:10:16
Original
1062 people have browsed it

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);
Copy after login

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);
Copy after login

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
}
Copy after login

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"
Copy after login

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 DBCP
Copy after login

http://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");
Copy after login

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);
}
}
Copy after login

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();
Copy after login

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

Use IOUtils

InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
try {
System.out.println( IOUtils.toString( in ) );
} finally {
IOUtils.closeQuietly(in);
}
Copy after login

2. Read file

File file = new File("/commons/io/project.properties");
List lines = FileUtils.readLines(file, "UTF-8");
Copy after login

3. Check the remaining space

long freeSpace = FileSystemUtils.freeSpace("C:/");
Copy after login

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;
}
}
Copy after login

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();
Copy after login

十五、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;
}
Copy after login

十六、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() );
}
Copy after login

从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);
Copy after login

以上就是java-类库-Apache Commons补充的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!