Java.io.BufferedInputStream.read() 方法



描述

java.io.BufferedInputStream.read(byte[] b, int off, int len) 方法將位元組輸入流中的 len 個位元組讀取到位元組陣列中,從給定的偏移量開始。此方法重複呼叫底層流的 read() 方法。

迭代讀取將持續到以下條件之一成立:

  • 讀取了 len 個位元組。

  • 返回 -1,表示檔案結尾。

  • 如果 BufferedInputStream 的 available() 方法返回 0

宣告

以下是 java.io.BufferedInputStream.read(byte[] b, int off, int len) 方法的宣告。

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

引數

  • b − 要填充的位元組陣列。

  • off − 從偏移量開始儲存。

  • len − 要讀取的位元組數。

返回值

此方法不返回值。

異常

IOException − 如果發生 I/O 錯誤。

示例

以下示例演示了 java.io.BufferedInputStream.read(byte[] b, int off, int len) 方法的使用。

package com.tutorialspoint;

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

public class BufferedInputStreamDemo {
   public static void main(String[] args) throws Exception {
      InputStream inStream = null;
      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 number of bytes available
         int numByte = bis.available();
         
         // byte array declared
         byte[] buf = new byte[numByte];
         
         // read byte into buf , starts at offset 2, 3 bytes to read
         bis.read(buf, 2, 3);
         
         // for each byte in buf
         for (byte b : buf) {
            System.out.println((char)b+": " + b);
         }
      } 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  

讓我們編譯並執行上述程式,這將產生以下結果:

  : 0
  : 0
A: 65
B: 66
C: 67
java_io_bufferedinputstream.htm
廣告
© . All rights reserved.