1 package arraylistplay; 2 3 /* 4 *Program featuring ArrayLists and IO to read and reverse copy some song lyrics 5 */ 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 = "Otherside.text"; 17 String outputFileName = "OthersideReversed.text"; 18 ArrayList<String> words = readWordsFromFile(inputFileName); 19 writeWordsToFile(words,outputFileName); 20 } 21 22 private static ArrayList<String> readWordsFromFile(String inputFileName) throws FileNotFoundException { 23 // Equate a scanner with the input file 24 Scanner scanner = establishScanner(inputFileName); 25 //Place lyrics from file into a dynamically growing ArrayList 26 ArrayList<String> words = new ArrayList<>(); 27 while ( scanner.hasNext() ) { 28 String word = scanner.next(); 29 words.add(word); 30 } 31 // Return the words 32 return words; 33 } 34 35 private static void writeWordsToFile(ArrayList<String> words, String outputFileName) 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 57 // found in the CS1Files/data subdirectory of the user’s home directory 58 59 private static String createFullFileName(String fileName) { 60 String separator = System.getProperty("file.separator"); 61 String home = System.getProperty("user.home"); 62 String path = home + separator + "CS1Files" + separator + "data" + separator; 63 String fullFileName = path + fileName; 64 return fullFileName; 65 } 66 } 67