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 中寫入資料的起始偏移量。

  • len − 讀取的最大位元組數。

返回值

此方法返回讀取的位元組數。

異常

  • NullPointerException − 如果 b 為 null

  • 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.htm
廣告