1 package arrayplay; 2 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.PrintWriter; 7 import java.util.Scanner; 8 9 public class ReverseCopy { 10 public static void main(String[] args) throws FileNotFoundException, IOException { 11 String inputFileName = "Lyrics.txt"; 12 String outputFileName = "Lyricsreversed.txt"; 13 String[] words = readWordsFromFile(inputFileName); 14 WriteWordsToFile(words, outputFileName); 15 } 16 17 private static final int LIMIT = 1000; 18 19 private static String[] readWordsFromFile(String inputFileName) throws FileNotFoundException { 20 // Scanner = input file 21 Scanner scan = establishScanner(inputFileName); 22 23 // Red words from the file into a oversized array 24 String[] temp = new String[LIMIT]; 25 int index = 0; 26 while (scan.hasNext()) { 27 String word = scan.next(); 28 temp[index] = word; 29 index = index + 1; 30 } 31 32 int wordCount = index; 33 34 //Transfer the words to a perfectly sized array 35 String[] words = new String[wordCount]; 36 for (int x = 0; x < wordCount; x = x + 1) { 37 words[x] = temp[x]; 38 } 39 // return words 40 return words; 41 } 42 43 private static void WriteWordsToFile(String[] words, String outputFileName) throws IOException { 44 // A printer is equal to an output file 45 PrintWriter print = getPrintWriter(outputFileName); 46 47 //Print words to the file 48 for (int x = words.length - 1; x >= 0; x = x - 1) { 49 print.println(words[x]); 50 } 51 print.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 60 private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException{ 61 String fullFileName = createFullFileName(outputFileName); 62 PrintWriter printer = new PrintWriter(fullFileName); 63 return printer; 64 } 65 66 // create full file name for simple file name, assuming that it will be 67 // found in the data directory 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 + "public_html" + separator + "data" + separator; 72 String fullFileName = path + FileName; 73 return fullFileName; 74 } 75 76 } 77