Java Reference
In-Depth Information
Answers to Self-Test Exercises
1. With an input stream, data flows from a file or input device to your program. With
an output stream, data flows from your program to a file or output device.
2. A binary file contains data that is processed as binary data. A text file allows your
program and editor to view the file as if it contained a sequence of characters. A
text file can be viewed with an editor, whereas a binary file cannot.
3 . A FileNotFoundException would be thrown if the file cannot be opened because,
for example, there is already a directory (folder) named stuff.txt . Note that
if the file does not exist but can be created, then no exception is thrown. If you
answered IOException , you are not wrong, because a FileNotFoundException
is an IOException . However, the better answer is the more specific exception
class—namely, FileNotFoundException .
4. No. This is why we use an object of the class FileOutputStream as an argument.
The correct way to express the code displayed in the question is as follows:
PrintWriter outputStream =
new PrintWriter( new FileOutputStream("stuff.txt"));
5 . PrintWriter outputStream =
new PrintWriter( new FileOutputStream("sam");
6 . PrintWriter outStream =
new PrintWriter( new FileOutputStream("sam", true ));
7. Yes, it will send suitable output to the text file because the class Person has a
well-defined toString() method.
8 . Scanner fileIn =
new Scanner( new FileInputStream("sally"));
9. It throws a NoSuchElementException if there are no more tokens. It throws an
InputMismatchException if the next token is not a well-formed string represen-
tation of an int . It throws an IllegalStateException if the Scanner stream
is closed.
10. No. Reading may have reached the end of the file, but another possibility is that
the next token may not be a well-formed string representation of an int value.
11. The FileInputStream constructor, and thus the Scanner constructor invocation,
can throw a FileNotFoundException . This exception needs to be caught or
declared in a throws clause.
12. BufferedReader fileIn =
new BufferedReader( new FileReader("joe"));
13. The method readLine returns a value of type String . The method read reads a
single character , but it returns it as a value of type int . To get the value to be of
type char , you need to do a type cast.
 
Search WWH ::




Custom Search