OCP OCP Java IO and NIO 1 — Questions and Answers
Question 1: Which Java class is designed specifically to read character data from a file using a character stream?
- FileInputStream
- FileReader (Correct answer)
- BufferedInputStream
- DataInputStream
Correct answer: FileReader
FileReader is a character stream (Reader subclass) that reads text data from a file, while FileInputStream reads raw bytes.
Question 2: What is the primary benefit of wrapping a FileWriter with a BufferedWriter in Java?
- It compresses data before writing to the file
- It reduces the number of actual write operations through internal buffering (Correct answer)
- It enables writing to multiple files simultaneously
- It automatically flushes on each write call
Correct answer: It reduces the number of actual write operations through internal buffering
BufferedWriter wraps another Writer with an internal buffer, batching multiple small writes into fewer, more efficient I/O operations.
Question 3: What exception type must be handled or declared when performing file I/O operations in Java?
- RuntimeException
- IOException (Correct answer)
- FileException
- StreamException
Correct answer: IOException
IOException is a checked exception that is the parent of all I/O-related exceptions and must be handled with try-catch or declared in the method signature.
Question 4: Which Java I/O class provides methods like readInt() and readDouble() to read primitive data types from a binary file?
- FileReader
- ObjectInputStream
- DataInputStream (Correct answer)
- RandomAccessFile
Correct answer: DataInputStream
DataInputStream wraps an InputStream and adds typed read methods for all Java primitive data types, making binary file parsing straightforward.
Question 5: What guarantee does the Java try-with-resources statement provide when used with I/O streams?
- Streams are opened only once per program run
- Streams are automatically closed when the try block exits (Correct answer)
- Exceptions thrown inside streams are always suppressed
- Streams are flushed to disk before the block exits
Correct answer: Streams are automatically closed when the try block exits
Try-with-resources automatically invokes close() on any AutoCloseable resource declared in the try header when the block completes, normally or exceptionally.
Question 6: Which method of the java.io.File class returns true if the file or directory at the specified path exists on the file system?
- isPresent()
- exists() (Correct answer)
- checkExists()
- fileFound()
Correct answer: exists()
The exists() method of java.io.File returns true if the abstract pathname denotes an existing file or directory on the filesystem.
Which Java class is designed specifically to read character data from a file using a character stream?