This quiz evaluates your understanding of Java I/O streams, character readers, and input/output handling best practices. Enhance your knowledge of Java file operations, stream types, and reader classes through scenario-based questions designed for intermediate learners.
Which Java class should you use to efficiently read lines of text from a file containing only characters?
Explanation: BufferedReader is designed for reading text efficiently from character input streams, making it ideal for reading lines from a text file. FileOutputStream is used for writing binary data, not reading. ObjectInputStream is for reading serialized objects rather than plain text. PrintStream is generally for writing output rather than reading input.
When working with FileInputStream and FileOutputStream in Java, which practice is recommended to ensure streams are always closed even if an exception occurs?
Explanation: Using the try-with-resources statement automatically closes streams after the try block, even if an exception is thrown, which helps prevent resource leaks. Wrapping streams in a DataReader has no effect on resource closure. Calling System.exit does not guarantee resource cleanup and abruptly ends the program. Opening streams in a static block is unrelated to closing resources safely.
If you want to read Unicode text data from a file in Java, which class should you generally prefer?
Explanation: FileReader reads character streams and properly handles Unicode text data, making it suitable for reading text files. FileInputStream reads raw bytes, not characters, so it would not properly interpret Unicode characters. ByteReader is not an existing Java class, and StreamScanner, which sounds similar to Scanner, is an incorrect option.
Which Java class is most appropriate for writing binary data, such as an image, to a file?
Explanation: FileOutputStream is intended for writing binary data to files, making it the correct choice for images or other non-text data. FileWriter and CharacterStreamWriter are designed for writing characters, not raw bytes, which can corrupt binary formats. BufferedReader is meant for reading text, not writing or handling binary data.
Which Java stream or reader often supports the mark and reset methods to revisit a specific point in the input stream?
Explanation: BufferedInputStream provides the ability to mark a position in the stream and later reset to that point, which is useful for repeated reads. FileOutputStream does not support reading or mark/reset functions. RandomTextReader and FilePrinter are not standard Java classes and thus are incorrect options.