1 package arraylistplay; 2 import java.io.File; 3 import java.io.FileNotFoundException; 4 import java.io.IOException; 5 import java.io.PrintWriter; 6 import java.util.ArrayList; 7 import java.util.Scanner; 8 public class ReverseCopy { 9 public static void main(String[] args) throws FileNotFoundException, IOException { 10 String inputFileName = "SongLyric2.text"; 11 String outputFileName = "SongLyric2Reversed.text"; 12 ArrayList<String> words = readWordsFromFile(inputFileName); 13 writeWordsToFile(words, outputFileName); 14 15 16 } 17 18 private static ArrayList<String> readWordsFromFile(String inputFileName) 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 the words 28 return words; 29 30 } 31 32 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 33 String fullFileName = createFullFileName(inputFileName); 34 return new Scanner(new File(fullFileName)); 35 } 36 37 private static String createFullFileName(String fileName) { 38 String separator = System.getProperty("file.separator"); 39 String home = System.getProperty("user.home"); 40 String path = home + separator + "CS1Files" + separator + "data" + separator; 41 String fullFileName = path + fileName; 42 return fullFileName; 43 } 44 45 46 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) throws IOException { 47 // Equate a printer with an output file 48 PrintWriter printer = getPrintWriter(outputFileName); 49 // Print the words to the file 50 for (int x = words.size() - 1; x >= 0; x = x - 1) 51 { 52 printer.println(words.get(x)); 53 } 54 printer.close(); 55 } 56 57 private static PrintWriter getPrintWriter(String outputFileName)throws FileNotFoundException { 58 String fullFileName = createFullFileName(outputFileName); 59 PrintWriter printer = new PrintWriter(fullFileName); 60 return printer; 61 } 62 } 63