Java.io.FileInputStream.read() 方法



描述

java.io.FileInputStream.read() 方法從該輸入流讀取一個位元組的資料。如果無可用輸入,則該方法將阻塞。

宣告

以下是 java.io.FileInputStream.read() 方法的宣告:

public int read()

引數

返回值

該方法返回下一個位元組的資料,如果到達檔案結尾則返回 -1。

異常

IOException − 如果發生 I/O 錯誤

示例

以下示例演示了 java.io.FileInputStream.read() 方法的用法。

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;
      
      try {
         // create new file input stream
         fis = new FileInputStream("C://test.txt");
         
         // read till the end of the file
         while((i = fis.read())!=-1) {
         
            // converts integer to character
            c = (char)i;
            
            // prints character
            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

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

ABCDEF
java_io_fileinputstream.htm
廣告