Java.io.FileInputStream.read() 方法



描述

java.io.FileInputStream.read(byte[] b, int off, int len) 方法最多讀取 len 位元組的資料,從該輸入流讀取到位元組陣列中,從目標陣列 b 中的偏移量 off 開始。

宣告

以下是 java.io.FileInputStream.read(byte[] b, int off, int len) 方法的宣告:

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

引數

  • b − 讀取資料的位元組陣列。

  • off − 目標陣列 b 中的起始偏移量。

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

返回值

該方法返回讀取到緩衝區中的總位元組數。

異常

  • IOException − 如果發生 I/O 錯誤。

  • NullPointerException − 如果 b 為 null。

  • IndexOutOfBoundsException − 如果 len 或 off 為負數,或者 b.length-off 大於 b.length。

示例

以下示例演示了 java.io.FileInputStream.read(byte[] b, int off, int len) 方法的用法。

package com.tutorialspoint;

import java.io.IOException;
import java.io.FileInputStream;

public class FileInputStreamDemo {
   public static void main(String[] args) throws IOException {
      FileInputStream fis = null;
      int i = 0;
      char c;
      byte[] bs = new byte[4];
      
      try {
         // create new file input stream
         fis = new FileInputStream("C://test.txt");
         
         // read bytes to the buffer
         i = fis.read(bs, 2, 1);
         
         // prints
         System.out.println("Number of bytes read: "+i);
         System.out.print("Bytes read: ");
         
         // for each byte in buffer
         for(byte b:bs) {
         
            // converts byte to character
            c = (char)b;
            if(b == 0)
               c = '-';
            
            // print
            System.out.print(c);
         } 
         
      } catch(Exception ex) {
         // if any error occurs
         ex.printStackTrace();
      } finally {
         // releases all system resources from the streams
         if(fis!=null)
            fis.close();
      }
   }
}

假設我們有一個文字檔案 c:/test.txt,其內容如下。此檔案將用作我們示例程式的輸入:

ABCDEF

讓我們編譯並執行上述程式,這將產生以下結果:

Number of bytes read: 1
Bytes read: --A-
java_io_fileinputstream.htm
廣告