001 002 import java.io.*; 003 import java.util.*; 004 005 /** 006 * Exercise 12.2 in the book. 007 * 008 * @author Kristian Torp 009 * @version 1.0 010 */ 011 public class Exercise12_2 { 012 013 public static void main(String[] args) { 014 String fileName; 015 // use command line argument if exists 016 if (args.length > 0) { 017 fileName = args[0]; 018 } else { 019 fileName = "Exercise12_1.java"; // this file 020 } 021 022 // place to store lines that are read 023 LinkedList ll = new LinkedList(); 024 BufferedReader in = null; 025 try { 026 // get the input 027 in = new BufferedReader(new FileReader(fileName)); 028 String line; 029 // loop through the lines in the file 030 while ((line = in.readLine()) != null) { 031 ll.add(line); 032 } 033 034 // write the lines in reverse order 035 for (int i = ll.size() - 1; i >= 0; i--) { 036 line = (String) ll.get(i); 037 System.out.println(line); 038 } 039 } catch (Exception e) { 040 System.out.println(e); 041 } finally { 042 // if the file has been opened then close it 043 if (in != null) { 044 try { 045 in.close(); 046 } catch (IOException e) { 047 System.out.println(e); 048 } 049 } 050 } 051 052 } 053 }