Apache Commons IO

Source: Internet
Author: User
Tags xml parser

1Overview

Commons io is a tool class library for developing IO streaming capabilities.

It consists of six main areas:

    • Tool Classes -- using static methods to perform common tasks

    • input -- for InputStream and Reader implementations

    • output -- for outputstream and Writer implementations

    • Filters -- Various file filter implementations

    • comparators --Java.util.Comparator implementations of various files

    • file Listener -- a component that listens for file system events

2User Guide

Commons IO includes tool class,endian classes, line iterator, file Filters, file comparators< /c4> and stream implementations.

See Javadocs For more detailed descriptions .

2.1Tool Class 2.1.1 Ioutils

Ioutils contains tool methods for handling read, write, and copy. Methods work for InputStream,outputstream,Reader, and Writer .

For example, from a the URL reads the bytes of the task, and prints them:

InputStream in = new URL ("http://commons.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://commons.apache.org"). OpenStream ();
try {
System.out.println (Ioutils.tostring (in));
} finally {
Ioutils.closequietly (in);
}

in some areas of application, these IO operations are common, and this class can save a lot of time. You can rely on well-tested code.

This kind of utility code, flexibility and speed is the most important. But you should also understand the limitations of this approach. Reading a 1 GB file using the above technique will result in an attempt to create a 1 GB string Object !

2.1.2 FileUtils

The FileUtils class contains tool methods that use the File object. Including read-write, copy, and more robust.

To read the entire file line:

File File = new file ("/commons/io/project.properties");
List lines = fileutils.readlines (file, "UTF-8");
2.1.3 Filenameutils

The Filenameutils class contains tool methods that do not need to use file objects to manipulate file names. This class is dedicated to masking the differences between Unix and Windows , avoiding transitions between these environments (for example, from development to production).

For example, the canonical file deletes two-point fragments:

String filename = "c:/commons/io/." /lang/project.xml ";
Return
2.1.4 Filesystemutils

The Filesystemutils class contains tool methods that use the file system access features that are not supported by the JDK. Currently, only the method that gets the space size of the drive is obtained. Note that this is the command line used, not the local code.

Long freeSpace = Filesystemutils.freespace ("c:/");
2.2 Endianclass

Different computer systems use different byte ordering conventions. In the so-called "Little Endian" architecture (for example , Intel), low bytes are stored in memory in lower addresses and subsequent bytes at higher addresses. For "Big EndIan" architectures, such as Motorola, the opposite is the case.

There are two classes in the association package:

    • The Endianutils class contains static methods that Exchange the endian-ness of Java primitives and streams .

    • The Swappeddatainputstream class is an implementation of the Datainput interface. Using it, we can read data from non-local endian-ness files.

See more details http://www.cs.umass.edu/~verts/cs32/endian.html .

2.3Row iterators

the Org.apache.commons.io.LineIterator class provides a flexible way to use a row-based file. You can create an instance directly, or through A factory method of FileUtils or Ioutils. Recommended usage mode:

Working with rows
} finally {
lineiterator.closequietly (iterator);
}
2.4file Filter

The Org.apache.commons.io.filefilter package defines an interface (Iofilefilter) that contains Java.io.FileFilter and Java.io.FilenameFilter. In addition, the package provides a range of ready-to-use Iofilefilter interface implementations, including implementations that allow you to combine other filters. These filters can be used to list files.

2.5file comparators

The Org.apache.commons.io.comparator package provides a series of java.io.File java.util.Comparator implementations. These comparators can be used to sort the file list and array.

2.6Flow

Org.apache.commons.io.input and org.apache.commons.io.output contain a variety of useful stream implementations.

    • empty output stream -- silently absorbing all the data sent to it.

    • Tee output Stream -- sends output data to two streams.

    • byte output stream - A more convenient version of the JDK class.

    • Compute Stream - The number of bytes passed by the statistic.

    • Proxy Flow -- delegate the appropriate method agent.

    • can be locked. writer-- uses file locks to provide synchronous Writer.

3Best Practices

This document is There is a series of " Best Practices " in the IO field .

3.1 Java.io.File

Typically, you must use the file and file name. There are many things that can go wrong:

    • A class can be working on Unix but not working on Windows (and vice versa)

    • Invalid path due to double or missing path delimiter

    • UNC file name ( on Windows) does not use the My local file name feature function

    • Wait a minute

These are good reasons not to use filenames as strings. Use java.io.File instead of dealing with many of the above scenarios. Therefore, our best practice is to use java.io.File instead of file name strings to avoid platform dependencies.

Commons-io 1.1 includes a class--filenameutils that focuses on file name processing . This handles many of these file name problems, however, it is still recommended, as far as possible, to use the Java.io.File object.

public static string GetExtension (string filename) {
int index = Filename.lastindexof ('. ');
if (index = =-1) {
Return "";
} else {
Return filename.substring (index + 1);
}
}

simple enough? Yes, but what happens if you pass in a full path instead of a file name? Take a look at the following, perfectly valid path:"C:\Temp\documentation.new\README". The definition in the above method returns "New\readme", which is certainly not what you want.

please use java.io.File instead of string. In FileUtils you will see function functions around java.io.File.

Not recommended:

String tmpdir = "/var/tmp";
String tmpfile = tmpdir + system.getproperty ("file.separator") + "test.tmp";
InputStream in = new Java.io.FileInputStream (tmpfile);

Recommended:

File Tmpdir = new file ("/var/tmp");
File Tmpfile = new file (Tmpdir, "test.tmp");
InputStream in = new Java.io.FileInputStream (tmpfile);
3.2Buffered Streams

IO Performance relies on buffering policies. In general, it is very fast to read packets of size up to or from a byte, because these sizes match the packet size in the file system or file system buffers on the hard disk. But as long as you read only a few bytes several times, performance definitely drops.

ensure that you have the correct buffer stream when you read or output streams, especially when working with files. Just use bufferedinputstream to decorate your fileinputstream.

InputStream in = new Java.io.FileInputStream (myfile);
try {
in = new Java.io.BufferedInputStream (in);
In.read (...)
} finally {
Ioutils.closequietly (in);
}

Note that the buffered stream is not buffered. Some components like The XML parser can do their own buffering, so do not need to decorate the InputStream incoming XML parser, but slow down your code. If you use copyutils or ioutils , you do not need to use an extra buffer stream


Apache Commons io

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.