1 /* //Program to read and reverse the copy of the lyric of the song 2 */ 3 4 5 6 package arraylistplay; 7 8 import java.io.File; 9 import java.io.FileNotFoundException; 10 import java.io.IOException; 11 import java.io.PrintWriter; 12 import java.util.ArrayList; 13 import java.util.Scanner; 14 15 public class ReverseCopy { 16 public static void main(String[] args) throws FileNotFoundException, IOException { 17 String inputFileName = "Happier.text"; 18 String outputFileName = "HappierReversed.text"; 19 ArrayList<String> words = readWordsFromFile(inputFileName); 20 writeWordsToFile(words,outputFileName); 21 } 22 23 private static ArrayList<String> readWordsFromFile(String inputFileName) 24 throws FileNotFoundException { 25 //Equate a scanner with the input file 26 Scanner scanner = establishScanner(inputFileName); 27 //read the word from the file into a dynamically growing ArrayList 28 ArrayList<String> words = new ArrayList<>(); 29 while (scanner.hasNext()) { 30 String word = scanner.next(); 31 words.add(word); 32 } 33 // Return the words 34 return words; 35 36 } 37 38 39 40 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) 41 throws IOException { 42 //Equate a printer with an output file 43 PrintWriter printer = getPrintWriter(outputFileName); 44 //print the word to the file 45 for (int x = words.size() - 1; x >= 0; x = x - 1) { 46 printer.println(words.get(x)); 47 } 48 printer.close(); 49 } 50 51 private static Scanner establishScanner(String inputFileName) 52 throws FileNotFoundException { 53 String fullFileName = createFullFileName(inputFileName); 54 return new Scanner(new File(fullFileName)); 55 } 56 57 58 private static PrintWriter getPrintWriter(String outputFileName) 59 throws FileNotFoundException { 60 String fullFileName = createFullFileName(outputFileName); 61 PrintWriter printer = new PrintWriter(fullFileName); 62 return printer; 63 } 64 65 //Create the full file name for a simple file name assuming that it willl be 66 //found in the CS1File/data subdirectory of the user's home directory 67 private static String createFullFileName(String fileName) { 68 String separator = System.getProperty("file.separator"); 69 String home = System.getProperty("user.home"); 70 String path = home + separator + "CS1Files" + separator + "data" + separator; 71 String fullFileName = path + fileName; 72 return fullFileName; 73 } 74 } 75 76 77