Friday, October 16, 2009

Code snippet to reverse the contents of a file (Java)

package reverse;

/* If contents of the file abc.txt are "Cricket is a religion in India", the below code will create a temp.txt file containing the output "aidnI ni noigiler a si tekcirC" */

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException;

public class Reverse {

 public static void main(String[] args) throws IOException 
 {
  FileReader fr=new FileReader("D:\\java\\workspace\\Reversefile\\src\\reverse\\abc.txt");//Enter full path of the file whose contents are to be reversed.
  
  
  BufferedReader br =new BufferedReader(fr);
  FileWriter fw=new FileWriter("temp.txt");
  String str="";
  while((str=br.readLine())!=null)
  {
   System.out.println(str);
   fw.write(new StringBuffer(str+"\n").reverse().toString());
   
  }
  fw.close();
  fr.close();
  br.close();
  
 }

}


No comments:

Post a Comment