Home » Java programming language

Java RandomAccessFile readChar() Method with Example

RandomAccessFile Class readChar() method: Here, we are going to learn about the readChar() method of RandomAccessFile Class with its syntax and example.
Submitted by Preeti Jain, on March 23, 2020

RandomAccessFile Class readChar() method

  • readChar() method is available in java.io package.
  • readChar() method is used to read a character value from this file and it can read character up to 2 bytes from the file.
  • readChar() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • readChar() method may throw an exception at the time of reading char.
    • IOException: This exception may throw an exception while performing input/output operation.
    • EOFException: This exception may throw when the file pointer reaches EOF (End-Of-File) before reading 2 bytes.

Syntax:

    public final char readChar();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is char, it returns the character of next 2 bytes from this file.

Example:

// Java program to demonstrate the example 
// of char readChar() method of
// RandomAccessFile

import java.io.*;

class RAFReadChar {
 public static void main(String[] args) throws Exception {
  // Instantiate a random access file
  // object with file name and permissions
  RandomAccessFile ra_f = new RandomAccessFile("e:/includehelp.txt", "rw");

  // By using writeChar() method is to 
  // write character to the file
  ra_f.writeChar('I');

  // Initially set the file pointer
  // is at 0 for reading the file
  ra_f.seek(0);

  // By using readChar() method is to 
  // read character from the file

  char ch = ra_f.readChar();
  System.out.println("ra_f.readChar(): " + ch);

  // By using close() method isto
  // close this stream ran_f
  ra_f.close();
 }
}

Output

ra_f.readChar(): I



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.