1 package arrayplay; 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.Scanner; 8 9 public class ReverseCopy { 10 public static void main (String [] args) throws FileNotFoundException, IOException { 11 String inputFileName = "Forever.txt"; 12 String outputFileName = "ForeverReversed.txt"; 13 String[] words = readWordsFromFile(inputFileName); 14 writeWordsToFile(words,outputFileName); 15 } 16 17 private static final int LIMIT = 1000; 18 19 private static void writeWordsToFile(String[] words, String outputFileName) throws IOException { 20 //equate a printer with an output file 21 PrintWriter printer = getPrintWriter(outputFileName); 22 //print words to the file 23 for(int x = words.length-1; x >= 0; x = x - 1) { 24 printer.println(words[x]); 25 } 26 printer.close(); 27 } 28 29 private static String[] readWordsFromFile(String inputFileName) throws FileNotFoundException { 30 //equate scanner with the input file 31 Scanner scanner = establishScanner(inputFileName); 32 String[] temp = new String[LIMIT]; 33 int index = 0; 34 while(scanner.hasNext()) { 35 String word = scanner.next(); 36 temp[index] = word; 37 index = index + 1; 38 } 39 int wordCount = index; 40 //transfer the words into a perfectly sized array 41 String[] words = new String[wordCount]; 42 for(int x = 0; x < wordCount; x = x + 1) { 43 words[x] = temp[x]; 44 } 45 //return the words 46 return words; 47 } 48 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 49 String fullFileName = createFullFileName(inputFileName); 50 return new Scanner(new File(fullFileName)); 51 } 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 }