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