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