Java.io.CharArrayReader.read() 方法



描述

java.io.CharArrayReader.read() 方法讀取單個字元。如果流結束,則返回 -1。

宣告

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

public int read()

引數

返回值

該方法返回讀取的字元,作為 0 到 65535 範圍內的整數。如果流已到達其末尾,則 read() 返回 -1。

異常

IOException - 如果發生任何 I/O 錯誤。

示例

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

package com.tutorialspoint;

import java.io.CharArrayReader;
import java.io.IOException;

public class CharArrayReaderDemo {
   public static void main(String[] args) {      CharArrayReader car = null;
      char[] ch = {'H', 'E', 'L', 'L', 'O'};
      
      try {
         // create new character array reader
         car = new CharArrayReader(ch);
         
         int value = 0;
         
         // read till the end of the file
         while((value = car.read())!=-1) {
            char c = (char)value;
            
            // print the character
            System.out.print(c+" : ");
            
            // print the integer
            System.out.println(value);
         }
         
      } catch(IOException e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         // releases any system resources associated with the stream
         if(car!=null)
            car.close();
      }
   }
}

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

H : 72
E : 69
L : 76
L : 76
O : 79
java_io_chararrayreader.htm
廣告

© . All rights reserved.