A developer is tasked with reading a large binary file (1 GB) from a network share using the least amount of memory possible. Which approach should be used?
Trap 1: Read the entire file into a byte array using Files.readAllBytes()
This loads the entire file into memory, which is not memory-efficient for large files.
Trap 2: Use a FileReader wrapped in a BufferedReader to read lines
FileReader is for character data, not binary files, and still holds data in memory.
Trap 3: Use a RandomAccessFile to read the file in segments
RandomAccessFile is not memory-efficient and is more complex; BufferedInputStream is simpler and adequate.
- A
Use a FileInputStream wrapped in a BufferedInputStream with a 8 KB buffer
This reads the file in chunks with a small buffer, minimizing memory footprint.
- B
Read the entire file into a byte array using Files.readAllBytes()
Why wrong: This loads the entire file into memory, which is not memory-efficient for large files.
- C
Use a FileReader wrapped in a BufferedReader to read lines
Why wrong: FileReader is for character data, not binary files, and still holds data in memory.
- D
Use a RandomAccessFile to read the file in segments
Why wrong: RandomAccessFile is not memory-efficient and is more complex; BufferedInputStream is simpler and adequate.