// CSE 143, Summer 2012 // Code written in lecture to reverse a file. // The two versions of the code we wrote have been factored into // methods so that you can view both. import java.util.*; import java.io.*; public class ReverseFile { public static void main (String[] args) throws FileNotFoundException{ reverseUsingAnArray(); System.out.println(); reverseUsingAnArrayList(); } // initial code using our 142 knowledge public static void reverseUsingAnArray() throws FileNotFoundException{ // hardcoding 1000 as the array size is bad! // the file we are reading could be longer or shorter String[] allWords = new String[1000]; int wordCount = 0; Scanner input = new Scanner(new File("poem.txt")); while(input.hasNext()) { allWords[wordCount] = input.next(); wordCount++; } // we have to start at wordCount NOT at allWords.length // as there may be extra space in the array if it is longer // than our file for (int i = wordCount - 1; i >= 0; i--) { System.out.print(allWords[i] + " "); } } // improved code transitioned to use an ArrayList public static void reverseUsingAnArrayList() throws FileNotFoundException{ ArrayList allWords = new ArrayList(); Scanner input = new Scanner(new File("poem.txt")); while(input.hasNext()) { allWords.add(input.next()); } for (int i = allWords.size() -1; i >= 0; i--) { System.out.print(allWords.get(i) + " "); } } }