當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。