Java-io-bytearrayinputstream-read

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

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

説明

  • java.io.ByteArrayInputStream.read()*メソッドは、この入力ストリームから次のバイトを読み取ります。 read()メソッドはブロックしません

宣言

以下は* java.io.ByteArrayInputStream.read()*メソッドの宣言です-

public int read()

パラメーター

NA

戻り値

0〜255の範囲のintとして値バイトを返します。 ストリームが終了した場合、-1を返します。

例外

NA

次の例は、java.io.ByteArrayInputStream.read()メソッドの使用法を示しています。

package com.finddevguides;

import java.io.ByteArrayInputStream;
import java.io.IOException;

public class ByteArrayInputStreamDemo {
   public static void main(String[] args) throws IOException {
      byte[] buf = {65, 66, 67, 68, 69};
      ByteArrayInputStream bais = null;

      try {
        //create new byte array input stream
         bais = new ByteArrayInputStream(buf);

         int b =0;

        //read till the end of the stream
         while((b = bais.read())!=-1) {

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

           //print
            System.out.println("byte :"+b+"; char : "+ c);

         }
         System.out.print(bais.read()+" Reached the end");

      } catch(Exception e) {
        //if I/O error occurs
         e.printStackTrace();
      } finally {
         if(bais!=null)
         bais.close();
      }
   }
}

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

byte :65; char : A
byte :66; char : B
byte :67; char : C
byte :68; char : D
byte :69; char : E
-1 Reached the end