Thursday, 30 May 2013

Java program to reverse the content of a text file

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
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 = filein.next();
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
if(!rev.isEmpty()){
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(iter.next() + " ");
out.close();
}

/**
* 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;
else
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