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
Thursday, October 28, 2010
Subscribe to:
Post Comments (Atom)
how to reverse the contents of a string from one file to another file
ReplyDeletehi
ReplyDeleteinput:
line1
line2
line3
output:
line3
line2
line1