ReverseCopy.java
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 = "Nirvana.text";
12           String outputFileName = "Nirvana.text";
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           // Equate a scanner with the input file
21           Scanner scanner = establishScanner(inputFileName);
22           // Read the words from the file into an oversized array
23           String[] temp = new String[LIMIT];
24           int index = 0;
25           while (scanner.hasNext()) {
26               String word = scanner.next();
27               temp[index] = word;
28               index = index + 1;
29           }
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           // Return the words
38           return words;
39       }
40   
41       private static void writeWordsToFile(String[] words, String outputFileName) throws IOException {
42           // Equate a printer with an output file
43           PrintWriter printer = getPrintWriter(outputFileName);
44           // Print the words to the file
45           for (int x = words.length - 1; x >= 0; x = x - 1) {
46               printer.println(words[x]);
47           }
48           printer.close();
49       }
50   
51       private static Scanner establishScanner(String inputFileName) throws FileNotFoundException {
52           String fullFileName = createFullFileName(inputFileName);
53           return new Scanner(new File(fullFileName));
54       }
55       private static PrintWriter getPrintWriter(String outputFileName) throws FileNotFoundException {
56       String fullFileName = createFullFileName(outputFileName);
57       PrintWriter printer = new PrintWriter(fullFileName);
58       return printer;
59       }
60       private static String createFullFileName(String fileName) {
61           String separator = System.getProperty("file.separator");
62           String home = System.getProperty("user.home");
63           String path = home + separator + "CS1Files" + separator + "data" + separator;
64           String fullFileName = path + fileName;
65           return fullFileName;
66       }
67   }
68