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
廣告