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 = "StarSpangledBanner.text"; 12 String outputFileName = "StarSpangledBannerReversed.text"; 13 String[] words = readWordsFromFile(inputFileName); 14 writeWordsToFile(words,outputFileName); 15 } 16 17 private static void writeWordsToFile(String[] words, String outputFileName) throws IOException { 18 // Equate a printer with an output file 19 PrintWriter printer = getPrintWriter(outputFileName); 20 // Print the words to the file 21 for(int x = words.length-1; x >= 0; x = x - 1){ 22 printer.println(words[x]); 23 } 24 printer.close(); 25 } 26 27 private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException { 28 String fullFileName = createFullFileName(outputFileName); 29 PrintWriter printer = new PrintWriter(fullFileName); 30 return printer; 31 } 32 33 private static final int LIMIT = 1000; 34 35 private static String[] readWordsFromFile(String inputFileName) throws FileNotFoundException { 36 //Equate a scanner with the input file 37 Scanner scanner = establishScanner(inputFileName); 38 // Read 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 = x + 1){ 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 a full file name for a simple file name, assuming that it will be found in the CS1/data subdirectory of the users home directory 62 private static String createFullFileName(String fileName) { 63 String separator = System.getProperty("file.separator"); 64 String home = System.getProperty("user.home"); 65 String path = home + separator + "CS1Files" + separator + "data" + separator; 66 String fullFileName = path + fileName; 67 return fullFileName; 68 } 69 } 70