1 /* 2 * Program featuring straight up arrays anf file IO ro read and reverse copy a lyric. 3 */ 4 5 package arrayplay; 6 7 import java.io.File; 8 import java.io.FileNotFoundException; 9 import java.io.IOException; 10 import java.io.PrintWriter; 11 import java.util.Scanner; 12 13 public class ReverseCopy { 14 public static void main(String[] args) throws FileNotFoundException, IOException { 15 String inputFileName = "OhWhy.text"; 16 String outputFileName = "OhWhyReverse.text"; 17 String[] words = readWordsFromFile(inputFileName); 18 writeWordsToFile(words,outputFileName); 19 } 20 21 private static final int LIMIT = 1000; 22 23 private static String[] readWordsFromFile(String inputFileName) throws FileNotFoundException { 24 // Equate a scanner with the input file 25 Scanner scanner = establishScanner(inputFileName); 26 // Read the words from the file into an oversized array 27 String[] temp = new String[LIMIT]; 28 int index = 0; 29 while ( scanner.hasNext() ) { 30 String word = scanner.next(); 31 temp[index] = word; 32 index = index + 1; 33 } 34 int wordCount = index; 35 // Transfer the words to a perfectly sized array 36 String[] words = new String[wordCount]; 37 for ( int x = 0; x < wordCount; x = x + 1) { 38 words[x] = temp[x]; 39 } 40 // Return the words 41 return words; 42 } 43 44 private static void writeWordsToFile(String[] words, String outputFileName) throws IOException { 45 // Equate a printer with an output file 46 PrintWriter printer = getPrintWriter(outputFileName); 47 // Print the words to the file\ 48 for ( int x = words.length-1; x >= 0; x = x - 1) { 49 printer.println(words[x]); 50 } 51 printer.close(); 52 } 53 54 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 55 String fullFileName = createFullFileName(inputFileName); 56 return new Scanner(new File(fullFileName)); 57 } 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 a simple file name, assuming that it will be 66 // found in the CS1/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