1 /* 2 * This program features an ArrayList to do its reverse copy thing 3 * from 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 = "YouAreTheReason.text"; 17 String outputFileName = "YouAreTheReasonReversed.text"; 18 ArrayList <String> words = readWordFromFile (inputFileName); 19 writeWordsToFile(words,outputFileName); 20 } 21 22 // private static final int LIMIT = 1000; 23 24 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) throws FileNotFoundException { 25 // Equate a printer with an output file 26 PrintWriter printer = getPrintWriter(outputFileName); 27 // Print the words to the file 28 for ( int x = words.size()-1; x>= 0; x = x-1) { 29 printer.println(words.get(x)); 30 } 31 printer.close(); 32 } 33 34 private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException { 35 String fullFileName = createFullFileName(outputFileName); 36 PrintWriter printer = new PrintWriter(fullFileName); 37 return printer; 38 } 39 40 private static ArrayList<String> readWordFromFile(String inputFileName) throws FileNotFoundException { 41 // Equate a scanner the input file 42 Scanner scanner = establishScanner (inputFileName); 43 // Red the words from the file into a dynamically growing ArrayList 44 // String[] temp = new String[LIMIT]; 45 ArrayList<String> words = new ArrayList<>(); 46 while ( scanner.hasNext() ) { 47 String word = scanner.next(); 48 words.add(word); 49 } 50 //return the words 51 return words; 52 } 53 54 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 55 String fullFileName = createFullFileName (inputFileName); 56 return new Scanner(new File(fullFileName)); 57 } 58 59 // Create the full file name for a simple file name, assuming that it will be 60 // found in the SC1Files/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