1 //Program that uses ArrayList to make a reverse copy of a file to a new file 2 package arraylistplay; 3 4 5 import java.io.File; 6 import java.io.FileNotFoundException; 7 import java.io.IOException; 8 import java.io.PrintWriter; 9 import java.util.ArrayList; 10 import java.util.Scanner; 11 12 public class ReverseCopy { 13 public static void main(String[] args) throws IOException { 14 String inputFileName = "ArianaSong"; 15 String outputFileName = "ArianaSongReversed"; 16 ArrayList<String> words = readWordsFromFile(inputFileName); 17 writeWordstoFile(words, outputFileName); 18 } 19 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 //read the words from the 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 36 37 private static void writeWordstoFile(ArrayList<String> words, String outputFileName) throws IOException { 38 //Equate a printer with and output file 39 PrintWriter printer = getPrintWriter(outputFileName); 40 //Print the words to the file 41 for(int x =words.size() - 1; x>= 0; x=x-1) { 42 printer.println(words.get(x)); 43 } 44 printer.close(); 45 } 46 47 48 49 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 50 String fullFileName = createFullFileName(inputFileName); 51 return new Scanner(new File(fullFileName)); 52 } 53 private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException { 54 String fullFileName = createFullFileName(outputFileName); 55 PrintWriter printer = new PrintWriter(fullFileName); 56 return printer; 57 } 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 } 68