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