Home »
Java programming language
Java RandomAccessFile readShort() Method with Example
RandomAccessFile Class readShort() method: Here, we are going to learn about the readShort() method of RandomAccessFile Class with its syntax and example.
Submitted by Preeti Jain, on March 23, 2020
RandomAccessFile Class readShort() method
- readShort() method is available in java.io package.
- readShort() method is used to read signed 16-bit short integer value from this RandomAccessFile.
- readShort() 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.
-
readShort() method may throw an exception at the time of reading short integer value.
- 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 short readShort();
Parameter(s):
- It does not accept any parameter.
Return value:
The return type of this method is short, it returns the 2 bytes of data from this RandomAccessFile manipulated as a short integer value.
Example:
// Java program to demonstrate the example
// of short readShort() method of
// RandomAccessFile
import java.io.*;
class RAFReadShort
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 writeShort() method is to
// write short to the file
ra_f.writeShort(10204);
// Initially set the file pointer
// is at 1 for reading the file
ra_f.seek(1);
// By using readShort() method is to
// read a short value up to signed 16 bit
// from this file
short s = ra_f.readShort();
System.out.println("ra_f.readShort(): " + s);
// By using close() method isto
// close this stream ran_f
ra_f.close();
}
}
Output
ra_f.readShort(): -9216