目录

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

描述 (Description)

java.io.BufferedInputStream.read(byte[] b, int off, int len)方法从字节输入流中读取len个字节,从给定的偏移量开始读取字节数组。 此方法重复调用基础流的read()方法。

迭代读取继续,直到其中一个后续条件成立为止 -

  • len字节读取。

  • 返回-1 ,表示文件结束。

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

声明 (Declaration)

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

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

参数 (Parameters)

  • b - 要填充的字节数组。

  • off - 从偏移开始存储。

  • len - 要读取的字节数。

返回值 (Return Value)

此方法不返回任何值。

异常 (Exception)

IOException - 如果发生I/O错误。

例子 (Example)

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

package com.iowiki;
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
↑回到顶部↑
WIKI教程 @2018