Thursday, October 28, 2010

Java program to reverse contents in a file

Below contains java program to read the contents of a file,reverse the contents of the file and write it back to the file.

1)create text.txt in D: drive of your system and type the contents say subin suresh
2)Create java class and type the below code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package reverse;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
*
* @author subin_s
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(new File("D:/test.txt")).useDelimiter("\\Z");
String contents = scanner.next();
System.out.println("Original String : " + contents);
contents = new StringBuffer(contents).reverse().toString();
System.out.println("Reversed String : " + contents);
FileWriter fstream = new FileWriter("D:/test.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(contents);
out.close();
}
}

3)Output
Original String : subin suresh
Reversed String : hserus nibus

2 comments:

  1. how to reverse the contents of a string from one file to another file

    ReplyDelete
  2. hi
    input:
    line1
    line2
    line3
    output:
    line3
    line2
    line1

    ReplyDelete