1 package arraylistplay; 2 //program that reads a file then makes a new file that reverses the words using array lists 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.PrintWriter; 7 import java.util.ArrayList; 8 import java.util.Scanner; 9 10 public class ReverseCopy { 11 public static void main(String[] args) throws FileNotFoundException,IOException{ 12 String inputFileName = "TheBird.txt"; 13 String outputFileName = "TheBirdReversed.txt"; 14 ArrayList<String> words = readWordsFromFile(inputFileName); 15 writeWordsToFile(words, outputFileName); 16 } 17 private static ArrayList<String> readWordsFromFile(String inputFileName) 18 throws FileNotFoundException{ 19 //equate a scanner with the input file 20 Scanner scanner = establishScanner(inputFileName); 21 //read the words from the 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 printer with an 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 private static PrintWriter getPrintWriter(String outputFileName) 46 throws FileNotFoundException{ 47 String fullFileName = createFullFileName(outputFileName); 48 PrintWriter printer = new PrintWriter(fullFileName); 49 return printer; 50 } 51 //create the full file name for a simpe file name, assuming that is will be 52 //found in the CS1Files/data subdirectory of the users home directory 53 private static String createFullFileName(String fileName){ 54 String separator = System.getProperty("file.separator"); 55 String home = System.getProperty("user.home"); 56 String path = home + separator + "CS1Files" + separator + "data" + separator; 57 String fullFileName = path + fileName; 58 return fullFileName; 59 } 60 } 61