CAP477 · Unit 5: Concurrency and I/O
File I/O and try-with-resources
8 practice questions
Key points
- Byte streams for binary, Reader/Writer for text
- try-with-resources closes in reverse order; close errors are suppressed
- FileNotFoundException and NoSuchFileException are IOExceptions
- transient fields are not serialized
Streams: byte streams (InputStream/OutputStream, e.g. FileInputStream, ByteArrayInputStream) handle raw bytes; character streams (Reader/Writer, e.g. FileReader, BufferedReader, BufferedWriter, PrintWriter) handle text. read() returns -1 at the end of a stream (65 B -1 for bytes 65, 66). Encoding matters: "Hé" is 2 chars but 3 bytes in UTF-8.
Modern API (`java.nio.file`): Files.writeString(path, text), Files.readString, Files.readAllLines ([a, b, c] for "a\nb\nc\n"), Files.size, Files.exists, Files.delete, option StandardOpenOption.APPEND to add to the end. Classic: BufferedReader.readLine() returns null at EOF; new FileWriter(file, true) appends.
Exceptions: I/O is checked. new FileReader("/no/such/file") throws FileNotFoundException and Files.readString on a missing path throws NoSuchFileException; both are IOExceptions.
try-with-resources closes every resource that implements AutoCloseable automatically, in reverse order of declaration (open A, open B, body, close B, close A). If the body throws and close() also throws, the close exception is kept as suppressed (getSuppressed()), and the body exception propagates.
Scanner parses tokens: nextInt(), next(), nextDouble(), nextLine(), hasNextLine(); nextInt() on non-numeric text throws InputMismatchException. Mixing nextInt() and nextLine() leaves the line break behind, so call an extra nextLine().
Serialization: a class implementing Serializable can be written with ObjectOutputStream. transient fields are not saved and come back as default values (pw -> null); writing a non-serializable object throws NotSerializableException.
Exam pitfall: forgetting to close a stream leaks the file handle; use try-with-resources.
Try two questions
What does BufferedReader.readLine() return at the end of the file?
- It throws EOFException
- null
- An empty string
- -1
Show the answer
B. The loop in the test ended after '2:line2'.
Which stream type is intended for reading text characters?
- InputStream
- ByteBuffer only
- Reader
- OutputStream
Show the answer
C. Reader subclasses decode bytes into characters.