1 2 3 /* 4 *Program featuring straight up arrays and file IO to read and reverse copy a lyric. 5 */ 6 7 package arrayplay; 8 9 import java.io.File; 10 import java.io.FileNotFoundException; 11 import java.io.IOException; 12 import java.io.PrintWriter; 13 import java.sql.SQLOutput; 14 import java.util.Scanner; 15 16 public class ReverseCopy{ 17 public static void main(String [] args) throws FileNotFoundException, IOException { 18 String inputFileName = "CountryRoads.text"; 19 String outputFileName = "CountryRoadsReversed.text"; 20 String[] words = readWordsFromFile(inputFileName); 21 writeWordsToFile(words,outputFileName); 22 } 23 24 private static final int LIMIT = 1000; 25 26 private static String[] readWordsFromFile(String inputFileName) throws FileNotFoundException { 27 // Equate a scanner with the input file 28 Scanner scanner = establishScanner(inputFileName); 29 //Read the words from the file into an poversized array 30 String[] temp = new String[LIMIT]; 31 int index = 0; 32 while (scanner.hasNext() ) { 33 String word = scanner.next(); 34 temp[index] = word; 35 index = index + 1; 36 } 37 int wordCount = index; 38 //Transfer the words to a perfectly sized array 39 String[] words = new String[wordCount]; 40 for ( int x = 0; x < wordCount; x = x + 1) { 41 words[x] = temp [x]; 42 } 43 //Return the words 44 return words; 45 } 46 private static void writeWordsToFile(String[] words,String outputFileName) throws IOException { 47 //Equate a printer with an output file 48 PrintWriter printer = getPrintWriter(outputFileName); 49 //Print the words to the file 50 for (int x = words.length - 1; x >= 0; x = x - 1) { 51 printer.println(words[x]); 52 } 53 printer.close (); 54 } 55 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 56 String fullFileName = createFullFileName(inputFileName); 57 return new Scanner(new File(fullFileName)); 58 } 59 private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException { 60 String fullFileName = createFullFileName(outputFileName); 61 PrintWriter printer = new PrintWriter(fullFileName); 62 return printer; 63 } 64 65 //Create the full file name for asimple file name, assuming that it will be 66 //found in the CS1Files/data subdirectory of the user's home directory. 67 68 private static String createFullFileName(String fileName) { 69 String separator = System.getProperty("file.separator"); 70 String home = System.getProperty("user.home"); 71 String path = home + separator + "CS1Files" + separator + "data" + separator; 72 String fullFileName = path + fileName; 73 return fullFileName; 74 75 } 76 77 } 78