IO与文件读写---使用Apache commons IO包提高读写效率

觉得很不错,就转载了, 作者: Paul Lin

 

首先贴一段Apache commons IO官网上的介绍,来对这个著名的开源包有一个基本的了解:
Commons IO is a library of utilities to assist with developing IO functionality. There are four main areas included:
●Utility classes - with static methods to perform common tasks ●Filters - various implementations of file filters
●Comparators - various implementations of java.util.Comparator for files ●Streams - useful stream, reader and writer implementations

[tr=none] [tr=none] [tr=none] [tr=none] [tr=none] [tr=none]
Packages
org.apache.commons.io This package defines utility classes for working with streams, readers, writers and files.
org.apache.commons.io.comparator This package provides various Comparator implementations for Files.
org.apache.commons.io.filefilter This package defines an interface (IOFileFilter) that combines both FileFilter and FilenameFilter.
org.apache.commons.io.input This package provides implementations of input classes, such as InputStream and Reader.
org.apache.commons.io.output This

【二】org.apache.comons.io.input包介绍
这个包针对SUN JDK IO包进行了扩展,实现了一些功能简单的IO类,主要包括了对字节/字符输入流接口的实现

附件: 你需要登录才可以下载或查看附件。没有帐号? 注册

这个包针对java.io.InputStream和Reader进行了扩展,其中比较实用的有以下几个:
●AutoCloseInputStream
Proxy stream that closes and discards the underlying stream as soon as the end of input has been reached or when the stream is explicitly closed. Not even a reference to the underlying stream is kept after it has been closed, so any allocated in-memory buffers can be freed even if the client application still keeps a reference to the proxy stream
This class is typically used to release any resources related to an open stream as soon as possible even if the client application (by not explicitly closing the stream when no longer needed) or the underlying stream (by not releasing resources once the last byte has been read) do not do that.
这个输入流是一个底层输入流的代理,它能够在数据源的内容被完全读取到输入流后,后者当用户调用close()方法时,立即关闭底层的输入流。释放底层的资源(例如文件的句柄)。这个类的好处就是避免我们在代码中忘记关闭底层的输入流而造成文件处于一直打开的状态。
我们知道对于某些文件,只允许由一个进程打开。如果我们使用后忘记关闭那么该文件将处于一直“打开”的状态,其它进程无法读写。例如下面的例子:

  1. new BufferedInputStream(new FileInputStream(FILE))
复制代码

里面的FileInputStream(FILE)在打开后不能被显式关闭,这将导致可能出现的问题。如果我们使用了 AutoCloseInputStream,那么当数据读取完毕后,底层的输入流会被自动关闭,迅速地释放资源。

  1. new BufferedInputStream(new AutoClosedInputStream(new FileInputStream));
复制代码 

你可能感兴趣的:(apache,commons)