Java.io.InputStream.read() 方法



描述

java.io.InputStream.read(byte[] b, int off, int len) 方法最多读取 len 个字节的数据,从输入流到字节数组。如果参数 len 为零,则不读取任何字节并返回 0;否则,尝试读取至少一个字节。如果流位于文件末尾,则返回的值为 -1。

声明

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

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

参数

  • b - 目标字节数组。

  • off - 数组 b 中写入数据的起始偏移量。

  • len - 要读取的字节数。

返回值

该方法返回读取到缓冲区中的字节总数,如果由于到达流的末尾而没有更多数据,则返回 -1。

异常

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

  • NullPointerException - 如果 b 为 null。

  • IndexOutOfBoundsException - 如果 off 为负数,len 为负数,或者 len 大于 b.length - off。

示例

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

package com.tutorialspoint;

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

public class InputStreamDemo {
   public static void main(String[] args) throws Exception {
      InputStream is = null;
      byte[] buffer = new byte[5];
      char c;
      
      try {
         // new input stream created
         is = new FileInputStream("C://test.txt");
         
         System.out.println("Characters printed:");
         
         // read stream data into buffer
         is.read(buffer, 2, 3);
         
         // for each byte in the buffer
         for(byte b:buffer) {
         
            // convert byte to character
            if(b == 0)
               
               // if b is empty
               c = '-';
            else
               
               // if b is read
               c = (char)b;
            
            // prints character
            System.out.print(c);
         }
         
      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases system resources associated with this stream
         if(is!=null)
            is.close();
      }
   }
}

假设我们有一个文本文件 c:/test.txt,其内容如下。此文件将用作我们示例程序的输入:

ABCDE

让我们编译并运行上述程序,这将产生以下结果:

Characters printed:
--ABC
java_io_inputstream.htm
广告
© . All rights reserved.