1 package arraylistplay; 2 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.PrintWriter; 7 import java.util.ArrayList; 8 import java.util.Scanner; 9 10 public class ReverseCopy2 { 11 public static void main(String[] args) throws FileNotFoundException, IOException { 12 String inputFileName = "SleepyPuppies.text"; 13 String outputFileName = "SleepyPuppiesReversed.text"; 14 ArrayList<String> words = readWordsFromFile(inputFileName); 15 writeWordsToFile(words, outputFileName); 16 } 17 18 private static final int LIMIT = 1000; 19 20 private static ArrayList<String> readWordsFromFile(String inputFileName) 21 throws FileNotFoundException { 22 //Equate a scanner with the input file 23 Scanner scanner = establishScanner(inputFileName); 24 //Read the words from the file into an over-sized array. 25 ArrayList<String> words = new ArrayList<String>(); 26 while (scanner.hasNext()) { 27 String word = scanner.next(); 28 words.add(word); 29 } 30 //Return the words 31 return words; 32 } 33 34 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) 35 throws IOException { 36 //Equate a printer with an output file. 37 PrintWriter printer = getPrinterWriter(outputFileName); 38 //Print the words to the file. 39 for (int x = words.size() - 1; x >= 0; x = x - 1) { 40 printer.println(words.get(x)); 41 } 42 printer.close(); 43 } 44 45 private static Scanner establishScanner(String inputFileName) 46 throws FileNotFoundException { 47 String fullFileName = createFullFileName(inputFileName); 48 return new Scanner(new File(fullFileName)); 49 } 50 51 private static PrintWriter getPrinterWriter(String outputFileName) throws FileNotFoundException { 52 String fullFileName = createFullFileName(outputFileName); 53 PrintWriter printer = new PrintWriter(fullFileName); 54 return printer; 55 } 56 57 private static PrintWriter getPrintWriter(String outputFileName) 58 throws FileNotFoundException { 59 String fullFileName = createFullFileName(outputFileName); 60 PrintWriter printer = new PrintWriter(fullFileName); 61 return printer; 62 } 63 //Create the full file name for a simple file name, assuming that it will be 64 //found in the CS1File/data subdirectory of the user's home directory. 65 private static String createFullFileName (String fileName){ 66 String separator = System.getProperty("file.separator"); 67 String home = System.getProperty("user.home"); 68 String path = home + separator + "CS1Files" + separator + "data" + separator; 69 String fullFileName = path + fileName; 70 return fullFileName; 71 72 } 73 } 74