1 /* //Program to read and reverse the copy of the lyric of the song 2 */ 3 4 5 6 package arrayplay; 7 8 import java.io.File; 9 import java.io.FileNotFoundException; 10 import java.io.IOException; 11 import java.io.PrintWriter; 12 import java.util.Scanner; 13 14 public class ReverseCopy { 15 public static void main(String[] args) throws FileNotFoundException, IOException { 16 String inputFileName = "Perfect.text"; 17 String outputFileName = "PerfectReversed.text"; 18 String[] words = readWordsFromFile(inputFileName); 19 writeWordsToFile(words,outputFileName); 20 } 21 22 private static final int LIMIT = 1000; 23 24 private static String[] readWordsFromFile(String inputFileName) throws FileNotFoundException { 25 //Equate a scanner with the input file 26 Scanner scanner = establishScanner(inputFileName); 27 //read the word from the file into oversizes array 28 String[] temp = new String[LIMIT]; 29 int index = 0; 30 while (scanner.hasNext()) { 31 String word = scanner.next(); 32 temp[index] = word; 33 index = index + 1; 34 } 35 int wordCount = index; 36 //transfer the words to a perfectly sized array 37 String[] words = new String[wordCount]; 38 for (int x = 0; x < wordCount; x = x + 1) { 39 words[x] = temp[x]; 40 41 } 42 //return the word 43 return words; 44 } 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 word 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 56 private static Scanner establishScanner(String inputFileName) throws FileNotFoundException { 57 String fullFileName = createFullFileName(inputFileName); 58 return new Scanner(new File(fullFileName)); 59 } 60 61 62 private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException { 63 String fullFileName = createFullFileName(outputFileName); 64 PrintWriter printer = new PrintWriter(fullFileName); 65 return printer; 66 } 67 68 //Create the full file name for a simple file name assuming that it willl be 69 //found in the CS1File/data subdirectory of the user's home directory 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 80