Java-io-bufferedinputstream-available

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

Java.io.BufferedInputStream.available()メソッドの例

説明

  • java.io.BufferedInputStream.available()*メソッドは、この入力ストリームのメソッドの次の呼び出しでブロックせずに入力ストリームから読み取るために残っているバイト数を返します。

宣言

以下は* java.io.BufferedInputStream.available()*メソッドの宣言です。

public int available()

戻り値

このメソッドは、ブロックせずにこの入力ストリームから読み取るために残った*バイト数*を返します。

例外

*IOException* -I/Oエラーが発生した場合。

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

package com.finddevguides;

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

public class BufferedInputStreamDemo {
   public static void main(String[] args) throws Exception {
      BufferedInputStream bis = null;

      try {
        //open input stream test.txt for reading purpose.
         inStream = new FileInputStream("c:/test.txt");

        //input stream is converted to buffered input stream
         bis = new BufferedInputStream(inStream);

        //read until a single byte is available
         while( bis.available() > 0 ) {

           //get the number of bytes available
            Integer nBytes = bis.available();
            System.out.println("Available bytes = " + nBytes );

           //read next available character
            char ch =  (char)bis.read();

           //print the read character.
            System.out.println("The character read = " + ch );
         }
      } catch(Exception e) {
         e.printStackTrace();
      } finally {
        //releases any system resources associated with the stream
         if(inStream!=null)
            inStream.close();
         if(bis!=null)
            bis.close();
      }
   }
}

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

ABCDE

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

Available bytes = 5
The character read = A
Available bytes = 4
The character read = B
Available bytes = 3
The character read = C
Available bytes = 2
The character read = D
Available bytes = 1
The character read = E