- Apache Commons IO 教程
- Apache Commons IO - 主页
- Apache Commons IO - 概述
- Apache Commons IO - 环境设置
- Apache Commons IO - IOUtils
- Apache Commons IO - FileUtils
- Apache Commons IO - FilenameUtils
- Apache Commons IO - FileSystemUtils
- Apache Commons IO - IOCase
- Apache Commons IO - LineIterator
- Apache Commons IO - NameFileFilter
- Apache Commons IO - WildcardFileFilter
- Apache Commons IO - SuffixFileFilter
- Apache Commons IO - PrefixFileFilter
- Apache Commons IO - OrFileFilter
- Apache Commons IO - AndFileFilter
- Apache Commons IO - FileEntry
- Apache Commons IO - FileAlterationObserver
- Apache Commons IO - FileAlterationMonitor
- Apache Commons IO - NameFileComparator
- Apache Commons IO - SizeFileComparator
- LastModifiedFileComparator
- Apache Commons IO - TeeInputStream
- Apache Commons IO - TeeOutputStream
- Apache Commons IO - 有用的资源
- Apache Commons IO - 快速指南
- Apache Commons IO - 有用的资源
- Apache Commons IO - 讨论
Apache Commons IO - IOUtils
IOUtils 提供用于读取、写入和复制文件的方法。该方法与 InputStream、OutputStream、Reader 和 Writer 一起使用。
类声明
以下是 org.apache.commons.io.IOUtils 类的声明 -
public class IOUtils extends Object
IOUtils 的特性
IOUtils 的特性如下 -
提供用于输入/输出操作的静态工具方法。
toXXX() - 从流中读取数据。
write() - 将数据写入流。
copy() - 将所有数据从一个流复制到另一个流。
contentEquals - 比较两个流的内容。
IOUtils 类的示例
这是我们需要解析的输入文件 -
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") );
}
}
}
Output
它将打印以下结果 -
Welcome to TutorialsPoint. Simply Easy Learning. Welcome to TutorialsPoint. Simply Easy Learning.
广告