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