- 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.
廣告