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 = "YouAreTheReason.text"; 12 String outputFileName = "YouAreTheReasonReversed.text"; 13 String[] words = readWordFromFile (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 FileNotFoundException { 20 // Equate a printer with an output file 21 PrintWriter printer = getPrintWriter(outputFileName); 22 // Print the 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 PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException { 30 String fullFileName = createFullFileName(outputFileName); 31 PrintWriter printer = new PrintWriter(fullFileName); 32 return printer; 33 } 34 35 private static String[] readWordFromFile(String inputFileName) throws FileNotFoundException { 36 // Equate a scanner the input file 37 Scanner scanner = establishScanner (inputFileName); 38 // Red the words from the file into an oversized array 39 String[] temp = new String[LIMIT]; 40 int index = 0; 41 while ( scanner.hasNext() ) { 42 String word = scanner.next(); 43 temp[index] = word; 44 index = index + 1; 45 } 46 int wordCount = index; 47 //Transfer the words to a perfectly sized array 48 String[] words = new String[wordCount]; 49 for ( int x = 0; x<wordCount; x++){ 50 words[x] = temp [x]; 51 } 52 //return the words 53 return words; 54 } 55 56 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 57 String fullFileName = createFullFileName (inputFileName); 58 return new Scanner(new File(fullFileName)); 59 } 60 61 // Create the full file name for a simple file name, assuming that it will be 62 // found in the SC1Files/data subdirectory of the user's home directory. 63 private static String createFullFileName(String fileName) { 64 String separator = System.getProperty("file.separator"); 65 String home = System.getProperty("user.home"); 66 String path = home + separator +"CS1Files" + separator + "data" + separator; 67 String fullFileName = path + fileName; 68 return fullFileName; 69 } 70 } 71