1 /* 2 * This program features an ArrayList to do its reverse copy thing 3 * from this 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 14 public class ReverseCopy { 15 public static void main(String[] args) throws FileNotFoundException, IOException { 16 String inputFileName = "DontFearTheReaper.text"; 17 String outputFileName = "DontFearTheReaperReverse.text"; 18 ArrayList<String> words = readWordsFromFile(inputFileName); 19 writeWordsToFile(words, outputFileName); 20 } 21 22 private static ArrayList<String> readWordsFromFile(String inputFileName) throws FileNotFoundException { 23 // Equate a scanner with the input file 24 Scanner scanner = establishScanner(inputFileName); 25 // Read the words from the file into an oversized array 26 ArrayList<String> words = new ArrayList<>(); 27 while ( scanner.hasNext() ) { 28 String word = scanner.next(); 29 words.add(word); 30 } 31 return words; 32 } 33 34 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) throws IOException { 35 // Equate a printer with an output file 36 PrintWriter printer = getPrintWriter(outputFileName); 37 // Print the words to file 38 for ( int x = words.size() - 1; x >= 0; x--) { 39 printer.println(words.get(x)); 40 } 41 printer.close(); 42 } 43 44 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 45 String fullFileName = createFullFileName(inputFileName); 46 return new Scanner(new File(fullFileName)); 47 } 48 49 private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException { 50 String fullFileName = createFullFileName(outputFileName); 51 PrintWriter printer = new PrintWriter(fullFileName); 52 return printer; 53 } 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 58 private static String createFullFileName(String fileName) { 59 String separator = System.getProperty("file.separator"); 60 String home = System.getProperty("user.home"); 61 String path = home + separator + "CS1Files" + separator + "data" + separator; 62 String fullFileName = path + fileName; 63 return fullFileName; 64 } 65 } 66