1 package arraylistplay; 2 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 12 public static void main(String[] args) throws FileNotFoundException, IOException { 13 String inputFileName = "Machine.text"; 14 String outputFileName = "MachineReversed.text"; 15 ArrayList<String> words = readWordsFromFile(inputFileName); 16 writeWordsToFile(words, outputFileName); 17 18 } 19 20 private static ArrayList<String> readWordsFromFile(String inputFileName) throws FileNotFoundException { 21 Scanner scanner = establishScanner(inputFileName); 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) throws IOException { 31 PrintWriter printer = getPrintWriter(outputFileName); 32 for (int x = words.size() - 1; x >= 0; x = x - 1) { 33 printer.println(words.get(x)); 34 } 35 printer.close(); 36 } 37 38 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 39 String fullFileName = createFullFileName(inputFileName); 40 return new Scanner(new File(fullFileName)); 41 42 } 43 44 private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException { 45 String fullFileName = createFullFileName(outputFileName); 46 PrintWriter printer = new PrintWriter(fullFileName); 47 return printer; 48 } 49 50 private static String createFullFileName(String fileName) { 51 String separator = System.getProperty("file.separator"); 52 String home = System.getProperty("user.home"); 53 String path = home + separator + "CS1Files" + separator + "data" + separator; 54 String fullFileName = path + fileName; 55 return fullFileName; 56 } 57 58 } 59