1 /* 2 * This program features an ArrayList to do its reverse copy thing from one file to another 3 */ 4 package arraylistplay; 5 import java.io.File; 6 import java.io.FileNotFoundException; 7 import java.io.IOException; 8 import java.io.PrintWriter; 9 import java.util.ArrayList; 10 import java.util.Scanner; 11 12 13 public class ReverseCopyOwn { 14 public static void main(String[] args) throws FileNotFoundException, IOException { 15 String inputFileName = "Rotten.text"; 16 String outputFileName = "RottenReversed.text"; 17 ArrayList<String> words = readWordsFromFile(inputFileName); 18 writeWordsToFile(words, outputFileName); 19 } 20 21 private static ArrayList<String> readWordsFromFile(String inputFileName) 22 throws FileNotFoundException { 23 // Equate a scanner with the input file 24 Scanner scanner = establishScanner(inputFileName); 25 // Read the words from the file into a dynamically growing ArrayList 26 ArrayList<String> words = new ArrayList<>(); 27 while (scanner.hasNext()) { 28 String word = scanner.next(); 29 words.add(word); 30 } 31 // Return the words 32 return words; 33 } 34 35 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) 36 throws IOException { 37 //Equate a printer with an output file 38 PrintWriter printer = getPrintWriter(outputFileName); 39 // Print the words to the file 40 for (int x = words.size() - 1; x >= 0; x = x-1) { 41 printer.println(words.get(x)); 42 } 43 printer.close(); 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 private static PrintWriter getPrintWriter(String outputFileName) 51 throws FileNotFoundException { 52 String fullFileName = createFullFileName(outputFileName); 53 PrintWriter printer = new PrintWriter(fullFileName); 54 return printer; 55 } 56 // Create the full file name for a simple file name, assuming that it will be 57 // found in the CS1File/data subdirectory of the user's home directory. 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 } 67