ReverseCopy.java
1    /* 
2     * This program features an ArrayList to do its reverse copy thing 
3     * from one file to another. 
4     */
5    
6    
7    package arraylistplay;
8    
9    import java.io.File;
10   import java.io.FileNotFoundException;
11   import java.io.IOException;
12   import java.io.PrintWriter;
13   import java.util.ArrayList;
14   import java.util.Scanner;
15   
16   public class ReverseCopy {
17   
18       public static void main(String[] args) throws FileNotFoundException, IOException{
19           String inputFileName = "DayN'Night.text";
20           String outputFileName = "DayN'NightReversed.text";
21           ArrayList<String> words = readWordsFromFile(inputFileName);
22           writeWordsToFile(words, outputFileName);
23       }
24   
25       private static ArrayList<String> readWordsFromFile(String inputFileName)
26               throws FileNotFoundException{
27           // Equate a scanner with the input file
28           Scanner scanner = establishScanner(inputFileName);
29           // Read the words from the file into a dynamically growing ArrayList
30           ArrayList<String> words = new ArrayList<>();
31           while (scanner.hasNext()) {
32               String word = scanner.next();
33               words.add(word);
34           }
35           // Return the words
36           return words;
37       }
38   
39       private static void writeWordsToFile(ArrayList<String> words, String outputFileName)
40               throws IOException {
41           // Equate a printer with an output file
42           PrintWriter printer = getPrintWriter(outputFileName);
43           // Print the words to the file
44           for (int x = words.size() -1; x>= 0; x = x - 1) {
45               printer.println(words.get(x));
46           }
47           printer.close();
48       }
49   
50       private static Scanner establishScanner(String inputFileName)
51               throws FileNotFoundException {
52           String fullFileName = createFullFileName(inputFileName);
53           return new Scanner(new File(fullFileName));
54       }
55   
56       private static PrintWriter getPrintWriter(String outputFileName)
57               throws FileNotFoundException {
58           String fullFileName = createFullFileName(outputFileName);
59           PrintWriter printer = new PrintWriter(fullFileName);
60           return printer;
61       }
62   
63       // Create the full file name for a simple file name, assuming that it will be
64       // found in the CS1/data subdirectory of the users 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