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