1 package arraylist; 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 = "HereComesTrouble.text"; 14 String outputFileName = "HereComesTroubleReversed.text"; 15 ArrayList<String> words = readWordsFromFile(inputFileName); 16 writeWordsToFile(words, outputFileName); 17 18 } 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 34 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) 35 throws IOException { 36 // Equate a printer with an output file 37 PrintWriter printer = getPrintWriter(outputFileName); 38 // Print the words to the file 39 for (int x = words.size() - 1; x >= 0; x = x - 1) { 40 printer.println(words.get(x)); 41 } 42 printer.close(); 43 } 44 45 private static Scanner establishScanner(String inputFileName) 46 throws FileNotFoundException { 47 String fullFileName = createFullFileName(inputFileName); 48 return new Scanner(new File(fullFileName)); 49 } 50 51 private static PrintWriter getPrintWriter(String outputFileName) 52 throws FileNotFoundException { 53 String fullFileName = createFullFileName(outputFileName); 54 PrintWriter printer = new PrintWriter(fullFileName); 55 return printer; 56 } 57 58 59 // Create the full file name for a simple file name, assuming that it will be 60 // found in the CS1Files/data subdirectory of the user’s home directory. 61 private static String createFullFileName(String fileName) { 62 String separator = System.getProperty("file.separator"); 63 String home = System.getProperty("user.home"); 64 String path = home + separator + "CS1Files" + separator + "data" + separator; 65 String fullFileName = path + fileName; 66 return fullFileName; 67 } 68 69 } 70