Quick revision
The short answer
The snippet has four problems. It ignores the value read() returns, so it does not know how many bytes it got, may stop early, and misses the -1 end-of-stream signal. new String(buf) decodes all 1,024 bytes, including unused zeros, with the default charset. The stream is not closed if an exception is thrown. The fix is try-with-resources plus Files.readString(path, StandardCharsets.UTF_8) or readAllBytes(), and a Reader when text must be streamed in chunks.
What to remember
In this answer, we saw that the snippet ignores the count that read() returns, decodes the whole buffer with the default charset, can split multi-byte characters, and leaks the stream on an exception. The fixes are to use try-with-resources, let Files.readString or readAllBytes read until the end, pass StandardCharsets.UTF_8 explicitly, and use a Reader when text has to be processed as a stream.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The snippet has four problems. It ignores the value read() returns, so it does not know how many bytes it got, may stop early, and misses the -1 end-of-stream signal. new String(buf) decodes all 1,024 bytes, including unused zeros, with the default charset. The stream is not closed if an exception is thrown. The fix is try-with-resources plus Files.readString(path, StandardCharsets.UTF_8) or readAllBytes(), and a Reader when text must be streamed in chunks.
Why this question is asked
Code like this appears in real projects because it works in the simplest test: a small ASCII file read on a developer's machine. It fails later with truncated content, strange characters at the end of strings, broken accents or leaked file handles. Interviewers use it as a code review exercise because each line hides a separate misunderstanding of how Java I/O behaves. In this answer, we will run the snippet against realistic inputs, look at each problem and why it happens, and then rewrite it correctly in a few ways depending on what we need.
1The Code Under Review
Here is the original code, formatted, and what it prints for a 5-byte file containing the word hello.
The string has 1,024 characters, not 5. The other 1,019 are the char with value 0, which is invisible when printed but breaks comparisons, JSON output and database columns. That is only the most visible of the problems.
2Problem 1: The Return Value of read() Is Ignored
InputStream.read(byte[]) does not promise to fill the array. It reads at least one byte, blocking until some are available, and returns how many it actually read, which can be anything from 1 to the array length. At the end of the stream it returns -1. A file stream often fills the buffer in one go for small files, but a network stream, a pipe or a decompressing stream regularly returns fewer bytes than asked.
So the snippet has two bugs here. For a file larger than 1,024 bytes it reads only the first chunk and silently drops the rest. For any stream that returns a short read, it keeps only part of the data even when the file is small. And because it never looks at the return value, it cannot tell an empty file, where read returns -1, from a full one. The rule is that every call to read must use its return value.
3Problem 2: Decoding the Whole Buffer With the Default Charset
new String(buf) decodes every byte in the array, not just the bytes that were read, which is where the 1,019 zero characters came from. It also uses the platform's default charset, because no charset is passed. Before Java 18 that depended on the operating system, so the same file could decode differently on Windows and Linux; since Java 18 it is UTF-8, but the code still does not say what format it expects.
There is a subtler issue too. If we fixed the length by writing new String(buf, 0, n, UTF_8) inside a loop that reads chunks, a multi-byte character could be split across two chunks. UTF-8 stores many characters in two to four bytes. If a chunk ends after the first byte of such a character, decoding that chunk alone produces a replacement character, and the next chunk starts with a stray byte that also becomes garbage.
The reason a Reader avoids this is that InputStreamReader keeps its decoder between reads. When a chunk ends in the middle of a character, the decoder holds the partial bytes and completes the character with the next read.
4Problem 3: The Stream Leaks When Something Fails
If read() throws an IOException, or if new String throws, the line in.close() never runs. Each FileInputStream holds an operating system file descriptor, and descriptors are a limited resource, often 1,024 or a few thousand per process. A service that leaks one on every failed request eventually fails with Too many open files. Before Java 7 we would close in a finally block; since Java 7, try-with-resources closes the stream automatically when the block exits, normally or by exception, and keeps the original exception if close also fails.
5The Fixed Versions
Which fix is best depends on the job. If we want the whole file as text, one call does everything right.
Notice what changed. try-with-resources guarantees closing. Files.readString and readAllBytes loop internally until the end of the stream, so short reads cannot truncate the data. The charset is explicit, so the result is the same on every platform and version. For large files that should not be loaded at once, a Reader streams text and handles characters that cross chunk boundaries. Files.readString does load the whole file into memory, so for a multi-gigabyte log the BufferedReader version is the right one.
6Follow-up questions
Is readNBytes different from readAllBytes?
Yes. readAllBytes reads until the end of the stream. readNBytes(buf, off, len), added in Java 9, keeps reading until it has exactly len bytes or reaches the end, and returns how many it got, so it is the right tool when a protocol says the next record is exactly 512 bytes. readNBytes(int len), added in Java 11, returns a new array of up to len bytes. Unlike plain read, both readNBytes forms block until the requested amount is in or the stream ends.
Why does trim() seem to fix the output?
String.trim() removes every character with a value up to and including space, and the char with value 0 is one of them, so trailing zeros disappear. But trim only hides the length problem; it does not fix short reads, lost data after the first 1,024 bytes, the charset or the leak, and it also strips real leading and trailing whitespace from the content.
7Conclusion
In this answer, we saw that the snippet ignores the count that read() returns, decodes the whole buffer with the default charset, can split multi-byte characters, and leaks the stream on an exception. The fixes are to use try-with-resources, let Files.readString or readAllBytes read until the end, pass StandardCharsets.UTF_8 explicitly, and use a Reader when text has to be processed as a stream.
Open with
I see four problems. First, read returns how many bytes it actually read, which can be fewer than the buffer, or -1 at the end of the stream, and the code ignores it.
Then, if they want more
So a file over 1,024 bytes is truncated, a stream that returns a short read loses data, and an empty file is not detected. Second, new String(buf) decodes the entire buffer, so for a five-byte file we get a 1,024-character string full of zero characters, and it uses the default charset, which before Java 18 depended on the platform.
Third, if read or the decoding throws, close is never called and we leak a file descriptor, which over time gives Too many open files. Fourth, even if we fixed the length and read in chunks, decoding each chunk separately breaks multi-byte UTF-8 characters that straddle a chunk boundary. My rewrite depends on the need.
For the whole file as text I would write Files.readString(path, StandardCharsets.UTF_8), which reads everything, decodes once and closes the file. For a general InputStream I would use try-with-resources and readAllBytes, then decode with an explicit charset. For a large text file I would use Files.newBufferedReader with UTF-8 and read line by line, because the Reader keeps decoder state across chunks.
And if I really need a manual byte loop, I always use the count: while n = read(buf) is not -1, write buf from 0 to n.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 18, Java 7, Java 9, Java 11
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Find the problems:": https://scrivio-interview-library.netlify.app/java/io-and-nio/086a8bbab2/