Thursday, 30 May 2013

Java program to reverse the content of a text file

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Scanner;

import javax.swing.JFileChooser;

 * This class reads a user chosen file, reads its words
 * reverses the order in which the words are stored in
 * the file i.e. the last word becomes first and the first
 * word becomes last.
 * @author Dixit Bhatta
 * **/
public class revFile {

public static void main(String[] args) throws IOException{
ArrayList<String> rev = new ArrayList<String>();//creating new ArrayList
String absolutePath = null; //to store path of the file
try {
File file = getInputFileNameFromUser();
//store the path of file to modify it later
absolutePath = file.getAbsolutePath();
Scanner filein = new Scanner(file); //open file
while(filein.hasNext()) {
String frame =;
rev.add(frame);// add the strings i.e. words to the ArrayList.
}//end of while

filein.close();//close the file

} catch (FileNotFoundException e) {//handle exception in case of error
System.err.println("FileNotFoundException: " + e.getMessage());

//display the number of words if it the file is not empty
int size = rev.size();
System.out.println("The number of words in file is: " + size);
Collections.reverse(rev);//reverse the arraylist
//use buffered writer and print writer to write into the file
BufferedWriter write = new BufferedWriter(new FileWriter(absolutePath));
PrintWriter out = new PrintWriter(write);
//writing the strings in the file using an iterator
Iterator<String> iter = rev.iterator();
while (iter.hasNext())
out.write( + " ");

* Lets the user select an input file using a standard file
* selection dialog box. If the user cancels the dialog
* without selecting a file, the return value is null.
static File getInputFileNameFromUser() {
JFileChooser fileDialog = new JFileChooser();
fileDialog.setDialogTitle("Select File for Input");
int option = fileDialog.showOpenDialog(null);
if (option != JFileChooser.APPROVE_OPTION)
return null;
return fileDialog.getSelectedFile();
}//end of choosing file


©Dixit Bhatta 2013

1 comment:

Was this post helpful? Ask any questions you have, I will try to answer them for you.

Follow by Email