Java-io-datainputstream-read-len

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

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

説明

  • java.io.DataInputStream.read(byte [] b、int off、int len)メソッドは、含まれる入力ストリームから *len バイトを読み取り、 b [off] から始まるバッファーbに割り当てます。 このメソッドは、入力データが使用可能になるか、例外がスローされるか、ファイルの終わりが検出されるまでブロックされます。

宣言

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

public final int read(byte[] b, int off, int len)

パラメーター

  • b -入力ストリームからデータが読み込まれるbyte []。
  • off -b []の開始オフセット。
  • len -読み取られた最大バイト数。

戻り値

読み込まれた合計バイト数。ストリームが最後に達した場合は-1。

例外

  • IOException -I/Oエラーが発生した場合、最初のバイトを読み取ることができないか、このメソッドの前にclose()が呼び出されます。
  • NullPointerException -bがnullの場合。
  • IndexOutOfBoundsException -lenがb.lengthより大きい場合-off、offは負、またはlenは負

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

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 input stream from file input stream
         is = new FileInputStream("c:\\test.txt");

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

        //count the available bytes form the input stream
         int count = is.available();

        //create buffer
         byte[] bs = new byte[count];

        //read len data into buffer starting at off
         dis.read(bs, 4, 3);

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

           //convert byte into character
            char c = (char)b;

           //empty byte as char '0'
            if(b == 0)
               c = '0';

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

      } catch(Exception e) {
        //if any I/O error occurs
         e.printStackTrace();
      } finally {
        //releases any associated system files with this stream
         if(is!=null)
            is.close();
         if(dis!=null)
            dis.close();
      }
   }
}

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

ABCDEFGH

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

0000ABC0