/home/ffrigin/NetBeansProjects/CS1/src/arraylistplay/ReverseCopy.java
 1 /*
 2 *This program features an ArrayList to do its reverse copy thing from one file to another.
 3  */
 4 package arraylistplay;
 5 
 6 import java.io.File;
 7 import java.io.FileNotFoundException;
 8 import java.io.IOException;
 9 import java.io.PrintWriter;
10 import java.util.ArrayList;
11 import java.util.Scanner;
12 
13 /**
14  *
15  *
16  * @author ffrigin
17  */
18 public class ReverseCopy {
19 
20     /**
21      * @param args the command line arguments
22      */
23     public static void main(String[] args) throws FileNotFoundException, IOException {
24         String inputFileName = "DontStopBelievin.text";
25         String outputFileName = "DontStopBelievinReversed.text";
26         ArrayList<String> words = readWordsFromFile(inputFileName);
27         writeWordsToFile(words, outputFileName);
28     }
29 
30     private static ArrayList<String> readWordsFromFile(String inputFileName) throws FileNotFoundException {
31         // Equate a scanner with the input file
32         Scanner scanner = establishScanner(inputFileName);
33         // Read the words from the file into a dynamically growing ArrayList
34         ArrayList<String> words = new ArrayList<>();
35 
36         while (scanner.hasNext()) {
37             String word = scanner.next();
38             words.add(word);
39         }
40         // Return the words
41         return words;
42     }
43 
44     private static void writeWordsToFile(ArrayList<String> words, String outputFileName) throws IOException {
45         // Equate a printer with an output file
46         PrintWriter printer = getPrintWriter(outputFileName);
47         // Print the words to the file
48         for (int x = words.size() - 1; x >= 0; x = x - 1) {
49             printer.println(words.get(x));
50         }
51         printer.close();
52     }
53 
54     private static Scanner establishScanner(String inputFileName) throws FileNotFoundException {
55         String fullFileName = createFullFileName(inputFileName);
56         return new Scanner(new File(fullFileName));
57     }
58 
59     private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException {
60         String fullFileName = createFullFileName(outputFileName);
61         PrintWriter printer = new PrintWriter(fullFileName);
62         return printer;
63     }
64 
65     // Create the full file name for a simple file name, assuming that it will be
66     // found in the CS1Files/data subdirectory of the user’s home directory.
67     private static String createFullFileName(String fileName) {
68         String separator = System.getProperty("file.separator");
69         String home = System.getProperty("user.home");
70 
71         String path = home + separator + "CS1Files" + separator + "data" + separator;
72         String fullFileName = path + fileName;
73         return fullFileName;
74     }
75 }
76