Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to copy a file into another file in reverse .

Java Code Example — File Handling Programs

ADVERTISEMENT

Java Program to copy a file into another file in reverse .

Objective

Write a Java program to copy a file in reverse using RandomAccessFile.

Algorithm / Approach

  1. Open the source file using a standard FileInputStream.
  2. Open the destination file using RandomAccessFile in "rw" (read-write) mode.
  3. Set the length of the destination file to match the source file.
  4. Set a position variable to the very end of the file (length).
  5. Read the source file character by character in a loop.
  6. For every character, convert it to bytes, subtract its length from position, move the cursor using raf.seek(position), and write it.
Reverse.java
import java.io.*;
import java.util.*;
class Reverse {
 public static void main(String[] a)
 {
  FileInputStream fis = null;
  RandomAccessFile raf = null; 
  Reader r = null;
  Scanner sc=new Scanner(System.in);
  System.out.print("Enter Source: ");
  String src = sc.nextLine();
  System.out.print("Enter Dest: ");
  String des = sc.nextLine();
  try{
   File in = new File(src);
   fis = new FileInputStream(in);
   r=new InputStreamReader(fis);
   File out = new File(des);
   raf = new RandomAccessFile(out,"rw");
   raf.setLength(in.length());
   char[] buff = new char[1];
   long position = in.length(); 
   while((r.read(buff))>-1) {
    Character c = buff[0];
    String s = c+"";
    byte[] bBuff = s.getBytes();
    position = position-bBuff.length;
    raf.seek(position);
    raf.write(bBuff);
   }
  System.out.println("Copied");
  }
  catch (Exception e) {
   System.out.print(e);
  } 
  finally {
   try {
    fis.close();
    raf.close();
   }
   catch (Exception e2) {
    System.out.print(e2);
   } 
  }
 }
}

Expected Output

Enter Source: dan.txt 
Enter Dest: prowess.txt     
Copied

Explanation of the Program

  • Standard I/O Streams are strictly sequential: you must read or write from the beginning to the end, in order.
  • RandomAccessFile breaks this rule. It acts like a large array of bytes stored on the hard drive. You can use the seek() method to instantly jump the cursor to any specific byte position in the file.
  • By starting our cursor at the very end of the destination file and moving backward for every character we read from the source, we effectively write the file in reverse.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT