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