Write a program to reverse the lines of a file and also to reverse the order of the words in each line of the file. Use ArrayList s to help you.
import java.io.File;
import java.io.*;
import java.util.*;
public class ReverseLines
{
public static void main(String[] args)
{
ArrayList<String> arrData = new ArrayList<String>();
try
{
File inFile = new File("lines.txt");
Scanner scn = new Scanner( inFile );
while ( scn.hasNextLine() ) {
arrData.add( scn.nextLine() );
}
} catch ( Exception ex )
{
System.out.println("Error found in input file...");
}
try
{
FileWriter outFile = new FileWriter("outputFile.txt");
for ( int i = arrData.size() - 1; i >= 0; i-- )
{
outFile.write(arrData.get(i)+"\n");
}
outFile.close();
} catch ( Exception e )
{
System.out.println("Error found in output file ");
}
}
}
Data in input file (lines.txt):
Welcome to sr2jr
Our Sr2jr team main theme is FREE
tradition of sharing subject knowledge.
Keep touch in sr2jr
Output in output file(outputFile.txt):
Keep touch in sr2jr
tradition of sharing subject knowledge.
Our Sr2jr team main theme is FREE
Welcome to sr2jr