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.ArrayList; 12 import java.util.Scanner; 13 public class ReverseCopy { 14 public static void main(String[] args) throws FileNotFoundException, IOException { 15 String inputFileName = "twinkle.text"; 16 String outputFileName = "TwinkleReversed.text"; 17 ArrayList<String> words = readWordsFromFile(inputFileName); 18 writeWordsToFile(words, outputFileName); 19 } 20 private static ArrayList<String> readWordsFromFile(String inputFileName) 21 throws FileNotFoundException { 22 // Equate a scanner with the input file 23 Scanner scanner = establishScanner(inputFileName); 24 // Read the words from the file into a dynamically growing ArrayList 25 ArrayList<String> words = new ArrayList<>(); 26 while (scanner.hasNext()) { 27 String word = scanner.next(); 28 words.add(word); 29 } 30 // Return the words 31 return words; 32 } 33 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) 34 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 private static Scanner establishScanner(String inputFileName) 44 throws FileNotFoundException { 45 String fullFileName = createFullFileName(inputFileName); 46 return new Scanner(new File(fullFileName)); 47 } 48 private static PrintWriter getPrintWriter(String outputFileName) 49 throws FileNotFoundException { 50 String fullFileName = createFullFileName(outputFileName); 51 PrintWriter printer = new PrintWriter(fullFileName); 52 return printer; 53 } 54 // Create the full file name for a simple file name, assuming that it will be 55 // found in the CS1Files/data subdirectory of the user’s home directory. 56 private static String createFullFileName(String fileName) { 57 String separator = System.getProperty("file.separator"); 58 String home = System.getProperty("user.home"); 59 String path = home + separator + "CS1Files" + separator + "data" + separator; 60 String fullFileName = path + fileName; 61 return fullFileName; 62 } 63 }