1 /* 2 * Program featuring straight up arrays and file IO to read and reverse copy a lyric. 3 */ 4 package arraylistplay; 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 = "ReadAllAboutIt.txt"; 15 String outputFileName = "ReadAllAboutItReversed.txt"; 16 ArrayList <String> words = readWordsFromFile(inputFileName); 17 writeWordsToFile(words, outputFileName); 18 } 19 private static final int LIMIT = 1000; 20 21 private static String[] readWordsFromFile (String inputFileName) throws FileNotFoundException { 22 //Equate a scanner with the input file 23 Scanner scanner = establishScanner(inputFileName); 24 // Read the words from the file intoan oversized array 25 String[] temp = new String[LIMIT]; 26 int index = 0; 27 while (scanner.hasNext()) { 28 String word = scanner.next(); 29 temp[index] = word; 30 index = index + 1; 31 } 32 int wordCount = index; 33 //Transfer the words to a perfectly sized array 34 String[] words = new String[wordCount]; 35 for (int x = 0; x < wordCount; x = x + 1) { 36 words[x] = temp[x]; 37 } 38 //RETURN THE WORDS 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 WORDS 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 private static PrintWriter getPrintWriter (String outputFileName) throws FileNotFoundException { 58 String fullFileName = createFullFileName(outputFileName); 59 PrintWriter printer = new PrintWriter(fullFileName); 60 return printer; 61 } 62 63 //CREATE THE FULL FILE NAME FOR A SIMPLE FILE NAME, ASSUMING THAT IT WILL BE FOUND IN THE CS1FILES/DATA 64 // SUBDIRECTORY OF THE USER'S HOME DIRECTORY 65 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 }