Java.io.FilterInputStream.read() 方法



描述

java.io.FilterInputStream.read() 方法從輸入流讀取下一個位元組的資料。返回的位元組值範圍為 0 到 255。如果到達檔案末尾,則方法返回 -1。

宣告

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

public int read()

引數

返回值

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

異常

IOException - 如果發生 I/O 錯誤

示例

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

package com.tutorialspoint;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FilterInputStreamDemo {
   public static void main(String[] args) throws Exception {
      InputStream is = null; 
      FilterInputStream fis = null; 
      int i = 0;
      char c;
      
      try {
         // create input streams
         is = new FileInputStream("C://test.txt");
         fis = new BufferedInputStream(is);
         
         // read till the end of the stream
         while((i = fis.read())!=-1) {
         
            // converts integer to character
            c = (char)i;
            
            // prints
            System.out.println("Character read: "+c);
         }
         
      } catch(IOException e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases any system resources associated with the stream
         if(is!=null)
            is.close();
         if(fis!=null)
            fis.close();
      }
   }
}

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

ABCDEF

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

Character read: A
Character read: B
Character read: C
Character read: D
Character read: E
Character read: F
java_io_filterinputstream.htm
廣告