Java Program using Recursion Write a program that reads in a
Java Program using Recursion:
Write a program that reads in a file and outputs it to another file. The output file created should be identical to the input file but with its lines in reverse order. Use recursion. Obtain the names of the input and output files from the command line. For the input file, use a file that contains the integers 1 to 10, each on a seperate line.
Solution
I think the given code is working correctly
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
public class Reversefile {
public static void main(String[] args) {
FileInputStream fis = null;
RandomAccessFile raf = null;
String characterEncoding = \"utf-8\";
if(args.length==3) {
characterEncoding = args[2];
}
try{
File in = new File(args[0]);
fis = new FileInputStream(in);
Reader r = new InputStreamReader(fis,characterEncoding);
File out = new File(args[1]);
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(characterEncoding);
position = position-bBuff.length;
raf.seek(position);
raf.write(bBuff);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e2) {
}
try {
raf.close();
} catch (Exception e2) {
}
}
}
}

