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 = "macmiller.text"; 12 String outputFileName = "macmillerReversed.text"; 13 String[] words = readWordsFromFile(inputFileName); 14 writeWordsToFile(words,outputFileName); 15 } 16 17 18 private static final int LIMIT = 1000; 19 20 private static String[] readWordsFromFile(String inputFileName) throws FileNotFoundException { 21 // Equate a scanner with the input file 22 Scanner scanner = establishScanner(inputFileName); 23 // read the words from the file into an oversized array 24 String[] temp = new String[LIMIT]; 25 int index = 0; 26 27 while ( scanner.hasNext()) { 28 String word = scanner.next(); 29 temp[index] = word; 30 index = index + 1; 31 } 32 int wordCount = index; 33 //Transfer the words to a perfectly sized array 34 String[] words = new String[wordCount]; 35 for (int x= 0 ; x < wordCount; x = x + 1) { 36 words[x] = temp[x]; 37 38 } 39 40 41 return words; 42 } 43 private static void writeWordsToFile(String[] words, String outputFileName) throws IOException { 44 // Equate a printer with a output file 45 PrintWriter printer = getPrintWriter(outputFileName); 46 for (int x = words.length-1; x>= 0; x=x-1) { 47 printer.println(words[x]); 48 } 49 50 printer.close(); 51 } 52 53 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 54 String fullFileName = createFullFileName(inputFileName); 55 return new Scanner(new File(fullFileName)); 56 } 57 58 private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException { 59 60 String fullFileName = createFullFileName(outputFileName); 61 PrintWriter printer = new PrintWriter(fullFileName); 62 return printer; 63 } 64 65 66 private static String createFullFileName(String fileName) { 67 68 String seperator = System.getProperty("file.separator"); 69 String home = System.getProperty("user.home"); 70 String path = home + seperator + "CS1Files" + seperator + "data" + seperator; 71 String fullFileName = path + fileName; 72 return fullFileName; 73 } 74 } 75