1 package arraylistplay; 2 3 /* 4 * This program features an ArrayList to do its reverse copy thing 5 * from one file to another. 6 */ 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 ReverseCopy { 16 17 public static void main(String[] args) throws FileNotFoundException, IOException 18 { 19 String inputFileName = "JetBlackHeart"; 20 String outputFileName = "JetBlackHeartReversed"; 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 { 33 String word = scanner.next(); 34 words.add(word); 35 } 36 // Return the words 37 return words; 38 } 39 40 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) 41 throws IOException { 42 // Equate a printer with an output file 43 PrintWriter printer = getPrintWriter(outputFileName); 44 // Print the words to the file 45 for(int x = words.size() - 1; x >= 0; x = x - 1) 46 { 47 printer.println(words.get(x)); 48 } 49 printer.close(); 50 } 51 52 private static Scanner establishScanner(String inputFileName) 53 throws FileNotFoundException { 54 String fullFileName = createFullFileName(inputFileName); 55 return new Scanner(new File(fullFileName)); 56 } 57 58 private static PrintWriter getPrintWriter(String outputFileName) 59 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 { 69 String separator = System.getProperty("file.separator"); 70 String home = System.getProperty("user.home"); 71 String path = home + separator + "CS1Files" + separator + "data" + separator; 72 String fullFileName = path + fileName; 73 return fullFileName; 74 } 75 } 76