Java.io.InputStream.read() 方法



描述

java.io.InputStream.read(byte[] b) 方法从输入流读取 b.length 个字节到缓冲区数组 b 中。读取的字节数以整数形式返回。

声明

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

public int read(byte[] b)

参数

b - 目标字节数组。

返回值

该方法返回实际读取到缓冲区的字节数,如果到达流的末尾则返回 -1。

异常

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

  • NullPointerException - 如果 b 为 null。

示例

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

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);
         
         // for each byte in the buffer
         for(byte b:buffer) {
         
            // convert byte to character
            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:
ABCDE
java_io_inputstream.htm
广告

© . All rights reserved.