public class FileReadCharsInteractive
1: //FileReadCharsInteractive.java
3: import java.util.Scanner;
4: import java.io.FileNotFoundException;
5: import java.io.FileReader;
6: import java.io.IOException;
8: public class FileReadCharsInteractive
9: {
10: /* Method prints characters in a file using read().
11: Throws IOException if read() operation fails.
12: */
13: public static void readFileChars(FileReader fileReader) throws IOException
14: {
15: int charRead; // Data read from file
17: charRead = 0;
19: // Use file input stream
20: System.out.print("Reading character values: ");
21: while (charRead != -1) // -1 means end of file has been reached
22: {
23: charRead = fileReader.read(); // May throw IOException
24: System.out.print(charRead + " ");
25: }
26: System.out.println();
27: }
29: /* Method closes a FileReader.
30: Prints exception message if closing fails. */
31: public static void closeFileReader(FileReader fileReader)
32: {
33: try
34: {
35: // Ensure fileReader references a valid object
36: if (fileReader != null)
37: {
38: System.out.println("Closing file.");
39: fileReader.close(); // close() may throw IOException if fails
40: }
41: }
42: catch (IOException closeExcpt)
43: {
44: System.out.println("Error closing file: " + closeExcpt.getMessage());
45: }
46: }
48: public static void main(String[] args)
49: {
50: Scanner scnr = new Scanner(System.in);
51: FileReader fileReader = null; // File stream for reading chars
52: String fileName; // User defined file name
53: boolean validFile; // Ensures file opened
55: validFile = true;
57: do
58: {
59: // Get file name from user
60: System.out.print("Enter a valid file name (or 'q' to quit): ");
61: fileName = scnr.next();
63: if (fileName.equals("q"))
64: {
65: break; // Exit do-while loop
66: }
68: try
69: {
70: // Prompt user for input
71: System.out.println("Opening file " + fileName + ".");
72: // May throw FileNotFoundException
73: fileReader = new FileReader(fileName);
75: // If reached this statement, file opened successfully.
76: validFile = true;
78: // Read chars from file
79: readFileChars(fileReader); // May throw IOException
80: }
81: catch (FileNotFoundException excpt)
82: {
83: System.out.println
84: (
85: "Caught FileNotFoundException: "
86: + excpt.getMessage()
87: );
88: validFile = false;
89: }
90: catch (IOException excpt)
91: {
92: System.out.println
93: (
94: "Caught IOException: "
95: + excpt.getMessage()
96: );
97: }
98: finally
99: {
100: closeFileReader(fileReader); // Ensure file is closed!
101: }
102: }
103: while (!validFile);
104: }
105: }