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