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