ReverseCopy.java
1    /* 
2     * This program features an ArrayList to do its reverse copy thing  
3     * from one file to another 
4     */
5    package ArrayListPlay;
6    
7    import java.io.File;
8    import java.io.FileNotFoundException;
9    import java.io.IOException;
10   import java.io.PrintWriter;
11   import java.util.ArrayList;
12   import java.util.Scanner;
13   
14   public class ReverseCopy {
15       public static void main(String[] args) throws FileNotFoundException, IOException {
16           String inputFileName = "Cuco.text";
17           String outputFileName = "CucoReversedList.text";
18           ArrayList<String> words = readWordsFromFile(inputFileName);
19           writeWordsToFile(words, outputFileName);
20       }
21   
22       private static ArrayList<String> readWordsFromFile(String inputFileName) throws FileNotFoundException {
23           // Equate a scanner with the input file
24           Scanner scanner = establishScanner(inputFileName);
25           // Read the words from the file into a dynamically growing ArrayList
26           ArrayList<String> words = new ArrayList<>();
27           while (scanner.hasNext()) {
28               String word = scanner.next();
29               words.add(word);
30           }
31           // Return the words
32           return words;
33       }
34   
35       private static void writeWordsToFile(ArrayList<String> words, String outputFileName) throws IOException {
36           // Equate a printer with an output file
37           PrintWriter printer = getPrinterWriter(outputFileName);
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) throws FileNotFoundException {
45           String fullFileName = createFullFileName(inputFileName);
46           return new Scanner(new File(fullFileName));
47       }
48   
49       private static PrintWriter getPrinterWriter(String outputFileName) throws FileNotFoundException {
50           String fullFileName = createFullFileName(outputFileName);
51           PrintWriter printer = new PrintWriter(fullFileName);
52           return printer;
53       }
54   
55       // Create the full file name for a simple file name, assuming that it will be
56       // found in the CS1Files/Data subdirectory of the user's home directory
57       private static String createFullFileName(String fileName) {
58           String separator = System.getProperty("file.separator");
59           String home = System.getProperty("user.home");
60           String path = home + separator + "CS1Files" + separator + "Data" + separator;
61           String fullFileName = path + fileName;
62           return fullFileName;
63       }
64   
65   }