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 10 public class ReverseCopy { 11 public static void main(String[] args) throws FileNotFoundException, IOException { 12 String inputFileName = "imagine.txt"; 13 String outputFileName = "imagineReversed.txt"; 14 String[] words = readWordsFromFile(inputFileName); 15 writeWordsToFile(words, outputFileName); 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 while (scanner.hasNext()) { 27 String word = scanner.next(); 28 temp[index] = word; 29 index = index + 1; 30 } 31 int wordCount = index; 32 // Transfer the words to a perfectly sized array 33 String[] words = new String[wordCount]; 34 for (int x = 0; x < wordCount; x = x + 1) { 35 words[x] = temp[x]; 36 } 37 // Return the words 38 return words; 39 } 40 41 private static void writeWordsToFile(String[] words, String outputFileName) throws IOException { 42 // Equate a printer with an output file 43 PrintWriter printer = getPrintWriter(outputFileName); 44 // Print the words to the file 45 for (int x = words.length - 1; x >= 0; x = x - 1) { 46 printer.println(words[x]); 47 } 48 printer.close(); 49 } 50 51 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 52 String fullFileName = createFullFileName(inputFileName); 53 return new Scanner(new File(fullFileName)); 54 } 55 56 private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException { 57 String fullFileName = createFullFileName(outputFileName); 58 PrintWriter printer = new PrintWriter(fullFileName); 59 return printer; 60 61 62 } 63 64 65 private static String createFullFileName(String fileName) { 66 String separator = System.getProperty("file.separator"); 67 String home = System.getProperty("user.dir");// Changed this from user.home in order to work on windows 68 String path = home + separator + "CS1Files" + separator + "data" + separator; 69 String fullFileName = path + fileName; 70 return fullFileName; 71 } 72 73 }