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