Java.io.RandomAccessFile.readChar() 方法



描述

java.io.RandomAccessFile.readChar() 方法從該檔案中讀取一個字元。此方法從檔案當前檔案指標處開始讀取兩個位元組。

宣告

以下是 java.io.RandomAccessFile.readChar() 方法的宣告。

public final char readChar()

引數

返回值

此方法返回該檔案的接下來的兩個位元組,解釋為一個字元。

異常

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

  • EOFException − 如果此檔案在讀取兩個位元組之前到達檔案末尾。

示例

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

package com.tutorialspoint;

import java.io.*;

public class RandomAccessFileDemo {
   public static void main(String[] args) {

      try {
         char c = 'H';
         
         // create a new RandomAccessFile with filename test
         RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

         // write something in the file
         raf.writeChar('C');

         // set the file pointer at 0 position
         raf.seek(0);

         // read char
         System.out.println("" + raf.readChar());

         // set the file pointer at 0 position
         raf.seek(0);

         // write a char at the start
         raf.writeChar(c);

         // set the file pointer at 0 position
         raf.seek(0);

         // read char
         System.out.println("" + raf.readChar());
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

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

ABCDE  

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

C
H
java_io_randomaccessfile.htm
廣告

© . All rights reserved.