Friday, 23 March 2018

Working with RandomAccessFile in Java

In this post, you are going to learn
a.   What is RandomAccessFile
b.   How to create an instance of RandomAccessFile?
c.   Important methods used while working with RandomAccessFile
d.   How can you read the data from file at random position?
e.   How can you write data to file from specific position?
f.    File tail implementation using RanddomAccessFile

What is RandomAccessFile?
You can read data from any position, write data at any position using RandomAccessFile.

RandomAccessFile treats the file data as an array of bytes, you can write the data at any position of the array and read the data from any position of the array.

How to create an instance of RandomAccessFile?
RandomAccessFile class provides below constructors, to create an instance of RandomAccessFile.

RandomAccessFile(File file, String mode)
RandomAccessFile(String filePath, String mode)

'mode' represents the accessMode to be used while opening the file.

Below table summarizes the possible values of the argument 'mode'.

Mode
Description
"r"
Opens the file in read only mode. If you try to perform any write operation, it results in IOException to be thrown
"rw"
Opens the file in read-write mode. You can perform both read and write operations here. If file is not exist already, it creates it.
"rws"
Opens the file in read-write mode. Opens the file in read-write mode. every update to the file's content or metadata be written synchronously to the underlying storage device.
"rwd"
Opens the file in read-write mode. Opens the file in read-write mode. Every update to the file's content be written synchronously to the underlying storage device.

Important methods used while working with RandomAccessFile
Below table summarizes the methods that you use frequently while working with RandomAccessFile.

Method
Description
public long getFilePointer()
Get the current position of the file pointer.
public void seek(long position)
Set the file pointer address. Position measured from the beginning of the file.
public long length()
Get the length of the file in bytes.
public void setLength(long newLength)
Set the length of the file in bytes.

If the present length of the file as returned by the length method is greater than the newLength argument then the file will be truncated. In this case, if the file offset as returned by the getFilePointer method is greater than newLength then after this method returns the offset will be equal to newLength.

If the present length of the file as returned by the length method is smaller than the newLength argument then the file will be extended. In this case, the contents of the extended portion of the file are not defined.
public int read(byte[] b)
Reads up to b.length bytes of data from this file into an array of bytes.

How can you read the data from file at random position?
By using below snippet, you can read the contents of the file.

RandomAccessFile randFile = new RandomAccessFile(filePath, "r")
randFile.seek(position);

byte b[] = new byte[BUFFER_SIZE];

while (randFile.read(b) != -1) {
         String s = new String(b);
         System.out.println(s);
}

testData.txt
If you can keep your head when all about you   
    Are losing theirs and blaming it on you,   
If you can trust yourself when all men doubt you,
    But make allowance for their doubting too;

Find the below working application.


FileUtil.java
package com.sample.util;

import java.io.IOException;
import java.io.RandomAccessFile;

public class FileUtil {

 private static final int BUFFER_SIZE = 4096;

 public static void prinFileContentFrom(String filePath, int position) throws IOException {
  try (RandomAccessFile randFile = new RandomAccessFile(filePath, "r")) {
   long length = randFile.length();

   if (position > length) {
    throw new IllegalArgumentException("position : " + position + " must be less than " + length);
   }

   randFile.seek(position);

   byte b[] = new byte[BUFFER_SIZE];

   while (randFile.read(b) != -1) {
    String s = new String(b);
    System.out.println(s);
   }
  }

 }
}


Test.java
package com.sample.test;

import com.sample.util.FileUtil;

public class Test {

 private static final String FILE_PATH = "C:\\Users\\krishna\\testData.txt";

 public static void main(String args[]) throws Exception {
  System.out.println("Reading the content from starting of the file");
  FileUtil.prinFileContentFrom(FILE_PATH, 0);

  System.out.println("\n*************************");
  System.out.println("Reading the content from the offset 50\n");
  FileUtil.prinFileContentFrom(FILE_PATH, 50);
 }
}

Output
Reading the content from starting of the file
If you can keep your head when all about you   
    Are losing theirs and blaming it on you,   
If you can trust yourself when all men doubt you,
    But make allowance for their doubting too;

*************************
Reading the content from the offset 50

   Are losing theirs and blaming it on you,   
If you can trust yourself when all men doubt you,
    But make allowance for their doubting too;

How can you write data to file from specific position?
Below snippet is used to write data to file from given position.

try (RandomAccessFile randFile = new RandomAccessFile(filePath, "rw")) {
         randFile.seek(position);
         randFile.write(data.getBytes());
}

Find the below working application.


FileUtil.java
package com.sample.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class FileUtil {

 private static final int BUFFER_SIZE = 4096;

 public static void writeContentsToFile(String filePath, String data, int position)
   throws FileNotFoundException, IOException {
  try (RandomAccessFile randFile = new RandomAccessFile(filePath, "rw")) {
   randFile.seek(position);
   randFile.write(data.getBytes());
  }
 }

 public static void printFileContent(String filePath) throws IOException{
  printFileContentFrom(filePath, 0);
 }
 
 public static void printFileContentFrom(String filePath, int position) throws IOException {
  try (RandomAccessFile randFile = new RandomAccessFile(filePath, "r")) {
   long length = randFile.length();

   if (position > length) {
    throw new IllegalArgumentException("position : " + position + " must be less than " + length);
   }

   randFile.seek(position);

   byte b[] = new byte[BUFFER_SIZE];

   while (randFile.read(b) != -1) {
    String s = new String(b);
    System.out.println(s);
   }
  }

 }
}


Test.java
package com.sample.test;

import com.sample.util.FileUtil;

public class Test {

 private static final String FILE_PATH = "C:\\Users\\krishna\\testData.txt";

 public static void main(String args[]) throws Exception {
  System.out.println("Reading the content from starting of the file");
  FileUtil.printFileContent(FILE_PATH);

  String data = "line1\nline2\nline3\nline4";

  System.out.println("\nDATA AFTER ADDING\n");

  FileUtil.writeContentsToFile(FILE_PATH, data, 50);
  
  FileUtil.printFileContent(FILE_PATH);

 }
}

Output
Reading the content from starting of the file
If you can keep your head when all about you   
    Are losing theirs and blaming it on you,   
If you can trust yourself when all men doubt you,
    But make allowance for their doubting too;
 
DATA AFTER ADDING

If you can keep your head when all about you   
 line1
line2
line3
line4d blaming it on you,   
If you can trust yourself when all men doubt you,
    But make allowance for their doubting too;








No comments:

Post a Comment