Java-io-datainputstream-readfully

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

Java.io.DataInputStream.readFully()メソッド

説明

  • java.io.DataInputStream.readFully(byte [] b)*メソッドは、入力ストリームからバイトを読み取り、それらをバッファー配列bに割り当てます。

以下の条件のいずれかが発生するまでブロックします-

  • b.lengthバイトの入力データが利用可能です。
  • ファイルの終わりが検出されました。
  • I/Oエラーが発生した場合。

宣言

以下は、* java.io.DataInputStream.readFully(byte [] b)*メソッドの宣言です-

public final void readFully(byte[] b)

パラメーター

NA

戻り値

このメソッドは値を返しません。

例外

  • IOException -I/Oエラーが発生した場合、またはストリームが閉じられた場合。
  • EOFException -この入力ストリームが前に終了した場合。

次の例は、java.io.DataInputStream.readFully(byte [] b)メソッドの使用法を示しています。

package com.finddevguides;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class DataInputStreamDemo {
   public static void main(String[] args) throws IOException {
      InputStream is = null;
      DataInputStream dis = null;

      try {
        //create file input stream
         is = new FileInputStream("c:\\test.txt");

        //create new data input stream
         dis = new DataInputStream(is);

        //available stream to be read
         int length = dis.available();

        //create buffer
         byte[] buf = new byte[length];

        //read the full data into the buffer
         dis.readFully(buf);

        //for each byte in the buffer
         for (byte b:buf) {

           //convert byte to char
            char c = (char)b;

           //prints character
            System.out.print(c);
         }

      } catch(Exception e) {
        //if any error occurs
         e.printStackTrace();
      } finally {
        //releases all system resources from the streams
         if(is!=null)
            is.close();
         if(dis!=null)
            dis.close();
      }
   }
}

テキストファイル* c:/test.txt*があり、次の内容があるとします。 このファイルは、サンプルプログラムの入力として使用されます-

Hello World!

上記のプログラムをコンパイルして実行すると、次の結果が生成されます-

Hello World!