devxlogo

Random File Access

Random File Access

Question:
I am trying to read from a text file using FileInputStream. Is there a way that I can go directly to the middle of the file and read from there?

Answer:
To perform random access operations on a file, such as seeking to a specific offset, you have to use RandomAccessFile rather than FileInputStream. Classes derived fromInputStream allow you only to read and skip data rather than arbitrarily access the input source. RandomAccessFile will let you seek to any position in a file through its seek(long offset) method, whichpositions the read/write pointer at a specified offset from the beginning of the file. To start reading a text file from the middle, you have to first determine its size, divide by two, and seek to that position before starting to read. The following code listing shows how to do this.

import java.io.*;/*** * This program opens a text file and prints out its contents a line * at a time starting from the middle of the file. ***/public class ReadMiddle {  public static void main(String[] args) {    File file;    RandomAccessFile input;    String line;    if(args.length != 1) {      System.err.println("Usage: ReadMiddle ");      return;    }    file = new File(args[0]);    if(!file.exists()) {      System.err.println(file + " doesn't exist!");      return;    }    try {      input = new RandomAccessFile(file, "r");    } catch(IOException e) {      e.printStackTrace();      return;    } catch(SecurityException e) {      System.err.println("Permission denied.");      return;    }    try {      input.seek(input.length()/2);      while((line = input.readLine()) != null)        System.out.println(line);    } catch(IOException e) {      e.printStackTrace();      return;    } finally {        input.close();      } catch(IOException e) {      }    }  }}          try {

See also  How to Avoid Money Transfer Scams  
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist