Random File Access

Random File Access

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?

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 {

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several