>  기사  >  Java  >  java-class 라이브러리-Apache Commons 보충 자료

java-class 라이브러리-Apache Commons 보충 자료

黄舟
黄舟원래의
2017-01-19 13:10:161046검색

Apache Commons에는 일상적인 프로그래밍에서 흔히 발생하는 문제를 해결하고 작업 중복을 줄이는 데 사용되는 많은 오픈 소스 도구가 포함되어 있습니다. 간략한 소개를 위해 일반적으로 사용되는 몇 가지 프로젝트를 선택했습니다. 이 기사는 인터넷에 있는 기성품을 많이 사용하여 방금 요약했습니다.

1. Commons BeanUtils
http://jakarta.apache.org/commons/beanutils/index.html
설명: Bean용 도구 세트입니다. Bean은 종종 일련의 get 및 set으로 구성되므로 BeanUtils도 이를 기반으로 일부 패키징을 수행합니다.

사용 예: 많은 기능이 있으며 웹사이트에 자세히 설명되어 있습니다. 가장 일반적으로 사용되는 기능 중 하나는 Bean의 속성을 복사하는 Bean Copy입니다. PO(영구 객체)에서 VO(값 객체)로 데이터를 복사하는 등 계층화된 아키텍처를 개발하는 경우에 사용됩니다.

기존 방식은 다음과 같습니다.

//得到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);

BeanUtils를 사용한 후 아래와 같이 코드가 크게 개선되었습니다.

//得到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
설명: 명령을 처리하는 도구입니다. 예를 들어, 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
}

3. Commons Codec
http://jakarta.apache.org/commons/codec/index.html
지침 : 이 도구는 Base64, URL, Soundx 등을 포함한 인코딩 및 디코딩에 사용됩니다. 이 도구를 사용하는 분들은 잘 아실 것이므로 자세히 소개하지는 않겠습니다.

4. Commons Collections
http://jakarta.apache.org/commons/collections/
참고: 이 도구를 java.util의 확장으로 생각할 수 있습니다.

사용예: 간단한 예를 들어보세요

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/
설명: 이 도구는 구성 파일을 처리하는 데 사용되며 다양한 저장 방법을 지원합니다

2. XML 문서

3. )

4. JDBC 데이터소스

6. 애플릿 매개변수

8 .

사용예: 간단한 속성 예시


# 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

http://jakarta.apache.org/commons/dbcp/
설명: 데이터베이스 연결 풀 , 이것이 Tomcat이 사용하는 것입니다. 더 말할 필요가 없습니다. 사용하려면 웹 사이트에 가서 지침을 읽으십시오.

6. Commons DbUtils
http://jakarta.apache.org/commons/dbutils/

참고: 저는 데이터베이스 프로그램을 작성할 때 데이터베이스 작업을 위해 별도의 패키지를 만드는 경우가 많았습니다. DbUtils는 그러한 도구이므로 향후 개발에서 이러한 작업을 반복할 필요가 없습니다. 이 도구는 널리 사용되는 OR 매핑 도구(예: 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");

와 같이 데이터베이스 작업만 단순화한다는 점을 언급할 가치가 있습니다. 7. 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);
}
}

8. 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();

9. Commons IO
http://jakarta.apache.org/commons/io/
설명: java.io의 확장이라고 볼 수 있는데, 사용하기 매우 편리하다고 생각합니다.

사용예:

1. 스트림 읽기

표준 코드:


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. 파일 읽기


으으으으
3. 남은 공간 확인


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

10. Commons JXPath

http://jakarta.apache.org/commons/jxpath/

설명: Xpath를 알고 있다면 JXpath는 Java 객체 기반 Xpath, 즉 Xpath를 사용하여 Java 객체를 쿼리합니다. 이 일은 여전히 ​​매우 상상력이 풍부합니다.

사용 예:


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

11. Commons Lang
http://jakarta.apache.org/commons/lang/
지침: This The 툴킷은 java.lang의 확장으로 볼 수 있습니다. StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils 등과 같은 도구 클래스를 제공합니다.

12. 커먼즈 로깅

http://jakarta.apache.org/commons/logging/

설명: Log4j를 아시나요?

13. Commons Math
http://jakarta.apache.org/commons/math/
설명: 이름을 보면 이 패키지의 용도를 알 수 있습니다. 이 패키지에서 제공하는 기능은 Commons Lang과 다소 중복되지만 이 패키지는 수학적 도구를 만드는 데 더 중점을 두고 있으며 더 강력한 기능을 가지고 있습니다.

14. Commons Net
http://jakarta.apache.org/commons/net/
참고: 이 패키지는 여전히 매우 실용적이며 많은 네트워크 프로토콜을 캡슐화합니다.

1. FTP

2. NNTP

4. POP3

6. TFTP

7. Finger

9. rexec/rcmd/rlogin

10. 🎜>
11. 에코

12. 폐기

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

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


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.