目录

Commons IO - IOUtils Class( IOUtils Class)

提供用于读取,写入和复制文件的实用方法。 这些方法适用于InputStream,OutputStream,Reader和Writer。

Class 声明 (Class Declaration)

以下是org.apache.commons.io.IOUtils类的声明 -

public class IOUtils
   extends Object

特点 (Features)

  • 为输入/输出操作提供静态实用程序方法。
  • toXXX() - 从流中读取数据。
  • write() - 将数据写入流。
  • copy() - 将所有数据复制到另一个流的流。
  • contentEquals - 比较两个流的内容。

IOUtils类的示例

这是我们需要解析的输入文件 -

Welcome to IoWiki. 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 IoWiki. Simply Easy Learning.
Welcome to IoWiki. Simply Easy Learning.
↑回到顶部↑
WIKI教程 @2018