Commons Io 简明教程
Apache Commons IO - IOUtils
IOUtils 提供用于读取、写入和复制文件的方法。这些方法可使用 InputStream、OutputStream、Reader 和 Writer。
IOUtils provide utility methods for reading, writing and copying files. The methods work with InputStream, OutputStream, Reader and Writer.
Class Declaration
下面是 org.apache.commons.io.IOUtils 类的声明 -
Following is the declaration for org.apache.commons.io.IOUtils Class −
public class IOUtils
extends Object
Features of IOUtils
以下为 IOUtils 的特性 -
The features of IOUtils are given below −
-
Provides static utility methods for input/output operations.
-
toXXX() − reads data from a stream.
-
write() − write data to a stream.
-
copy() − copy all data to a stream to another stream.
-
contentEquals − compare the contents of two streams.
Example of IOUtils Class
以下是我们需要解析的输入文件 -
Here is the input file we need to parse −
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.io.IOUtils;
public class IOTester {
public static void main(String[] args) {
try {
//Using BufferedReader
readUsingTraditionalWay();
//Using IOUtils
readUsingIOUtils();
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
//reading a file using buffered reader line by line
public static void readUsingTraditionalWay() throws IOException {
try(BufferedReader bufferReader = new BufferedReader( new InputStreamReader(
new FileInputStream("input.txt") ) )) {
String line;
while( ( line = bufferReader.readLine() ) != null ) {
System.out.println( line );
}
}
}
//reading a file using IOUtils in one go
public static void readUsingIOUtils() throws IOException {
try(InputStream in = new FileInputStream("input.txt")) {
System.out.println( IOUtils.toString( in , "UTF-8") );
}
}
}