1 package arraylists; 2 import java.io.File; 3 import java.io.FileNotFoundException; 4 import java.io.IOException; 5 import java.io.PrintWriter; 6 import java.util.ArrayList; 7 import java.util.Scanner; 8 9 10 public class reverseCopy { 11 public static void main(String[] args) throws FileNotFoundException, IOException{ 12 String inputFileName = "Ozymandias.text"; 13 String outputFileName = "OzymandiasReversed.text"; 14 ArrayList<String> words = readWordsFromFile(inputFileName); 15 writeWordsToFile(words, outputFileName); 16 } 17 private static ArrayList<String> readWordsFromFile(String inputFileName) 18 throws FileNotFoundException { 19 //equate scanner with input file 20 Scanner scanner = establishScanner(inputFileName); 21 //read words from file into a dynamically growing arraylist 22 ArrayList<String> words = new ArrayList<>(); 23 while (scanner.hasNext()) { 24 String word = scanner.next(); 25 words.add(word); 26 } 27 return words; 28 } 29 30 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) 31 throws IOException { 32 // equate a printer w/ output file 33 PrintWriter printer = getPrintWriter(outputFileName); 34 //print the words to the file 35 for (int x = words.size()-1; x >= 0; x = x -1) { 36 printer.println(words.get(x)); 37 } 38 printer.close(); 39 } 40 private static Scanner establishScanner(String inputFileName) 41 throws FileNotFoundException{ 42 String FullFileName = createFullFileName(inputFileName); 43 return new Scanner(new File(FullFileName)); 44 45 46 } 47 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 67 68 69 70 71 72 73 74 75 76