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