Java.io.RandomAccessFile Class

Random.AccessFile class inherits Objects class and implements DataOutput, DataInput and Closeable interfaces. This class supports both reading from and writing to a random access file . A random access file behaves like a large array of bytes stored in the file system.
There is a file pointer in the implied array, input operations read bytes starting at the file pointer . If the file is opened in read-write mode, then the output operations are also available.
Output operations write bytes starting at the file pointer.
File Opening modes
“r” Open file for reading only.
“rw” Open file for reading and writing. If file does not exist , then an attempt will be made to create it.
“rwd” Open file for reading and writing and also required that every up- date to the file’s content be written synchronously to the underly-ing storage device.
  • void seek(long) and long getFilePointer()
Using Seek(long) method, you can set the file pointer offset, measured from the beginning of the file, at the file, at where next read or write occurs. The offset may be set beyond the end of file. Offset is measured in byte from the beginning of life. If offset position is less than zero or if I/O error occurs, it throws IOException.
  • getFilePointer()method returns the current offset in the file. If an I/O error occurs it throws IOException.
  • void writeUTF() and void readUTF()
void writeUTF() writes a string to the file using modified UTF-8 encoding in a machine independent manner . Its Firsts 2 Bytes consists of the number of bytes to follow not the length of string.
  • final String readUTF() throws IOException
This method reads a string from file . The string has been encoded using modified UTF-8 format . The first 2 byte are read to set of number of bytes that are encoded string. The following bytes are then interpreted as bytes encoding characters in the modified UTF-8 format and converted into characters.
The following program shows how to use writeUTF(), readUTF(),seek() and setFilePointer() methods to work with random access files.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileClass {
    public static void main(String[] args) {
        try {
          RandomAccessFile raf = new RandomAccessFile("books.txt", "rw");
          String books[] = new String[5];
            books[0] = "Thinking In Java";
            books[1] = "Java SCJP";
            books[2] = "Java Security";
            books[3] = "Complete Reference";
            books[4] = "Real Java";
            for (int i = 0; i < books.length; i++) 
            	System.out.println(" Writing to file :"+books[i]);
            //positioning the File Pointer at the end of file using seek()
            raf.writeUTF("Servlet & JSP Programming");
            System.out.println("........Writing Completed.......");

            // Move the file pointer to the beginning of the file
            System.out.println("=== Reading From File===");
           while (raf.getFilePointer() < raf.length())
        catch (FileNotFoundException e)
        catch (IOException e) 
       Writing to file :Thinking In Java
       Writing to file :Java SCJP
       Writing to file :Java Security
       Writing to file :Complete Reference
       Writing to file :Real Java
       ........Writing Completed.......
       === Reading From File===
       Thinking In Java
       Java SCJP
       Java Security
       Complete Reference
       Real Java
       Servlet & JSP Programming

Scanner Class

The scanner class is a class provider in java.util package. This class allows the user to read values of various types.It allows us to read numeric values from either the keyword or file without having to convert them from strings.
There are two constructor that are particularly useful:
  • Scanner(InputStream source)
  • Scanner(File source) throws FileNotFoundException
First constructor takes an InputStream object as a parameter and the other takes a File object as a parameter.
Commonly used methods of Scanner class are listed below:
Method Description
int nextInt() Returns the next token as an int.
long nextLong() Returns the next token as an long.
float nextFloat() Returns the next token as an float.
double nextDouble() Returns the next token as an double.
String next() Returns a token ended by white space
String nextLine() Returns the whole line up to end.
Void close() Closes the scanner.
The following program Input data from use.
import java.util.Scanner;
import java.io.*;  
public class ScannerClass
  public static void main(String[] args)
    // Declarations
    Scanner in = new Scanner(System.in);
    int rollno;
    float percentage;
   String name;
       // Prompts
    System.out.print("Enter your Roll no,Percentage and Name ");
    System.out.println("( Separate with a space):");   
    // Read in values  
    rollno = in.nextInt();
    percentage = in.nextFloat();
    name = in.nextLine();
    System.out.println("Here is what you entered: ");
    System.out.println("Roll no=" + rollno+" Percentage=" +percentage + " Name=" + name );
    Enter your Roll no,Percentage and Name ( Separate with a space):
    123 90.9 Rajesh Bansal
    Here is what you entered: 
    Roll no=123 Percentage=90.9 Name= Rajesh Bansal

ObjectInputStream & ObjectOutputStream Classes

ObjectInputStream and ObjectoutputStream classes are the parts of java.io package. objectInputStream is derivied from InputStream Class and implements ObjectInput interface and class ObjectOutputStream is derived from OutputStream and implements Interface ObjectOutput.
These classes are used for serialization and deserialization of objects . To write objects on underlying stream is known as serialization and to read them back is known as deserialization. The underlying stream may be a file or disk or network connection(socket).
To serialize object, you need some OutputStream object, which must be wrapped inside ObjectOutputStream, then call its writeObject() method. On the other side to deserialize, you need to reverse the process by wrapping an InputStream object inside ObjectInputStream object and call its readObject() method, what you receive is a reference to the object class instance. So you must downcast to make it work properly, shown as follows:
Serialization Process
Deserialization Process
The following programs writes the serialization object in file and deserialize the it to read the file:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Company implements Serializable
		String name,webSite;
		Company(String n,String ws)
			name=n; webSite=ws;
	 String getCompDetails()
			return "Company Name="+name+ " Site="+webSite;	

class SerialzeProcess 
		void serializeObject(Company p)
			FileOutputStream fos=new FileOutputStream("file2.txt");
			ObjectOutputStream oos=new ObjectOutputStream(fos);
			System.out.println("Object Serialized Successfully.....");
			catch(Exception ex){ex.printStackTrace();}
	void deserializeObject()
				System.out.println("------  deserializing-------");
				FileInputStream fos=new FileInputStream("file2.txt");
				ObjectInputStream oos=new ObjectInputStream(fos);
				Company pp=(Company)oos.readObject();
				System.out.println("Object deserialized Successfully.....");
				catch(Exception ex){ex.printStackTrace();}
public class ObjectInpuOutputStreams 
	public static void main(String[] args) 
		SerialzeProcess sp=new SerialzeProcess();
		Company pro=new Company("Dell", "www.dell.com");
Object Serialized Successfully.....
------  deserializing-------
Company Name=Dell Site=www.dell.com
Object deserialized Successfully.....


About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
20 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android,MERN Stack(MongoDB,Express,ReactJS,NodeJS). If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : bcebti@gmail.com #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap