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
- Open the source file using a standard
FileInputStream. - Open the destination file using
RandomAccessFilein "rw" (read-write) mode. - Set the length of the destination file to match the source file.
- Set a
positionvariable to the very end of the file (length). - Read the source file character by character in a loop.
- For every character, convert it to bytes, subtract its length from
position, move the cursor usingraf.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.
RandomAccessFilebreaks this rule. It acts like a large array of bytes stored on the hard drive. You can use theseek()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)