Home » Java programming language

Java RandomAccessFile readUTF() Method with Example

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

RandomAccessFile Class readUTF() method

  • readUTF() method is available in java.io package.
  • readUTF() method is used to read this RandomAccessFile as a string.
  • readUTF() 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.
  • readUTF() method may throw an exception at the time of reading the file as a string.
    • 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 all bytes.
    • UTFDataFormatException: This exception may throw when the bytes denote invalid UTF-8 encoding schemes.

Syntax:

    public final String readUTF();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is String, it gets Unicode string value.

Example:

// Java program to demonstrate the example 
// of String readUTF() method of
// RandomAccessFile

import java.io.*;

class RAFReadUTF {
 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 writeUTF() method is to 
  // write data to the file
  ra_f.writeUTF("Welcome in Java World!!!");

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

  // By using readUTF() method is to 
  // read a data in a string from
  // this file

  //String str = ra_f.readUTF();
  System.out.println("ra_f.readUTF(): " + ra_f.readUTF());

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

Output

ra_f.readUTF(): Welcome in Java World!!!


Comments and Discussions!

Load comments ↻





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