当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Java Java.io.SequenceInputStream.read()用法及代码示例


描述

这个java.io.SequenceInputStream.read(byte[] b,int off,int len)方法从这个输入流中读取最多 len 个字节的数据到一个字节数组中。如果 len 不为零,则该方法将阻塞,直到至少有 1 个字节的输入可用;否则,不读取任何字节并返回 0。

声明

以下是声明java.io.SequenceInputStream.read()方法。

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

参数

  • b− 读取数据的缓冲区。

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

  • b− 读取的最大字节数。

返回值

此方法返回读取的字节数。

异常

  • NullPointerException− 如果 b 为空

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

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

示例

下面的例子展示了使用java.io.SequenceInputStream.read()方法。

package com.tutorialspoint;

import java.io.*;

public class SequenceInputStreamDemo {
   public static void main(String[] args) {

      // create two  new strings with 5 characters each
      String s1 = "Hello";
      String s2 = "World";

      // create 2 input streams
      byte[] b1 = s1.getBytes();
      byte[] b2 = s2.getBytes();
      ByteArrayInputStream is1 = new ByteArrayInputStream(b1);
      ByteArrayInputStream is2 = new ByteArrayInputStream(b2);

      // create a new Sequence Input Stream
      SequenceInputStream sis = new SequenceInputStream(is1, is2);

      // create a new byte array
      byte arr[] = {'1', '2', '3', '4'};
      
      try {
         // read 3 chars and print the number of chars read
         System.out.print("" + sis.read(arr, 0, 3));

         // change line
         System.out.println();

         // close the streams
         sis.close();

      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

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

3

相关用法


注:本文由纯净天空筛选整理自 Java.io.SequenceInputStream.read() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。