ReverseCopy.java
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 ReverseCopy {
11   
12       public static void main(String[] args) throws FileNotFoundException, IOException {
13           String inputFileName = "SunriseSunburnSunset.text";
14           String outputFileName = "SunriseSunburnSunsetReversed.text";
15           ArrayList<String> words = readWordsFromFile(inputFileName);
16           writeWordsToFile(words, outputFileName);
17       }
18   
19       private static ArrayList<String> readWordsFromFile(String inputFileName)
20               throws FileNotFoundException {
21           // Equate a scanner with the input file
22           Scanner scanner = establishScanner(inputFileName);
23           // Read the words from the file into a dynamically growing ArrayList
24           ArrayList<String> words = new ArrayList<>();
25           while (scanner.hasNext()) {
26               String word = scanner.next();
27               words.add(word);
28           }
29           // Return the words
30           return words;
31       }
32   
33       private static void writeWordsToFile(ArrayList<String> words, String outputFileName)
34               throws IOException {
35           // Equate a printer with an output file
36           PrintWriter printer = getPrintWriter(outputFileName);
37           //Print words to the file
38           for (int x = words.size()-1; x >= 0; x = x - 1) {
39               printer.println(words.get(x));
40           }
41           printer.close();
42       }
43   
44       private  static Scanner establishScanner(String inputFileName)
45               throws FileNotFoundException {
46           String fullFileName = createFullFileName(inputFileName);
47           return new Scanner(new File(fullFileName));
48       }
49   
50       private static PrintWriter getPrintWriter(String outputFileName)
51               throws FileNotFoundException {
52           String fullFileName = createFullFileName(outputFileName);
53           PrintWriter printer = new PrintWriter(fullFileName);
54           return printer;
55       }
56       // Create the full file name for a simple file name, assuming that it will be
57       // found in the the CS1Files/data subdirectory of the user's home directory.
58       private static String createFullFileName(String fileName) {
59           String separator = System.getProperty("file.separator");
60           String home = System.getProperty("user.home");
61           String path = home + separator + "CS1Files" + separator + "data" + separator;
62           String fullFileName = path + fileName;
63           return fullFileName;
64       }
65   
66   
67   }