Java.io.InputStream.read() 方法



描述

java.io.InputStream.read() 方法從輸入流讀取下一個位元組的資料,並返回範圍在 0 到 255 之間的整數。如果由於到達流的末尾而沒有可用的位元組,則返回值為 -1。

宣告

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

public abstract int read()

引數

返回值

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

異常

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

示例

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

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;
      int i;
      char c;
      
      try {
         // new input stream created
         is = new FileInputStream("C://test.txt");
         
         System.out.println("Characters printed:");
         
         // reads till the end of the stream
         while((i = is.read())!=-1) {
         
            // converts integer to character
            c = (char)i;
            
            // 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
廣告