Commons-io-ioutils

提供:Dev Guides
移動先:案内検索

Apache Commons IO-IOUtils

ファイルの読み取り、書き込み、コピーのためのユーティリティメソッドを提供します。 このメソッドは、InputStream、OutputStream、Reader、Writerで機能します。

クラス宣言

以下は org.apache.commons.io.IOUtils クラスの宣言です-

public class IOUtils
   extends Object

特徴

  • 入出力操作用の静的ユーティリティメソッドを提供します。
  • toXXX()-ストリームからデータを読み取ります。
  • write()-データをストリームに書き込みます。
  • copy()-すべてのデータをストリームから別のストリームにコピーします。
  • contentEquals-2つのストリームの内容を比較します。

IOUtilsクラスの例

ここに解析する必要がある入力ファイルがあります-

Welcome to finddevguides. 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") );
      }
   }
}

出力

次の結果が出力されます。

Welcome to finddevguides. Simply Easy Learning.
Welcome to finddevguides. Simply Easy Learning.