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