SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Arraylists
Exercise:
Programming Projects
Question:2 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.