Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Apr 5, 1999

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 from InputStream 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, which positions 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 {      
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date