1 package arraylistplay; 2 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.PrintWriter; 7 import java.util.ArrayList; 8 import java.util.Scanner; 9 10 public class ReverseCopy { 11 12 public static void main(String[] args) throws FileNotFoundException, IOException { 13 String inputFileName = "Pray.txt"; 14 String outputFileName = "PrayReversed.txt"; 15 ArrayList<String> words = readWordsFromFile(inputFileName); 16 writeWordsToFile(words, outputFileName); 17 } 18 19 private static ArrayList<String> readWordsFromFile(String inputFileName) throws FileNotFoundException { 20 // Equate a scanner with the input file 21 Scanner scanner = establishScanner(inputFileName); 22 // Read the words from the file into a dynamically growing ArrayList 23 ArrayList<String> words = new ArrayList<>(); 24 while (scanner.hasNext()) { 25 String word = scanner.next(); 26 words.add(word); 27 } 28 // Return the words 29 return words; 30 } 31 32 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) throws IOException { 33 // Equate a printer with an output file 34 PrintWriter printer = getPrintWriter(outputFileName); 35 // Print the words to the file 36 for (int x = words.size() - 1; x >= 0; x = x - 1) { 37 printer.println(words.get(x)); 38 } 39 printer.close(); 40 } 41 42 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 43 String fullFileName = createFullFileName(inputFileName); 44 return new Scanner(new File(fullFileName)); 45 } 46 47 private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException { 48 String fullFileName = createFullFileName(outputFileName); 49 PrintWriter printer = new PrintWriter(fullFileName); 50 return printer; 51 } 52 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 }