An importer needs a limit on accepted input work as well as a parser. This lesson reads lines through an injected Reader, enforces a maximum number of physical lines, and keeps resource ownership explicit. Browser examples use StringReader; the same core can later sit behind a local file adapter.
Understand the contract
Reader is a library abstraction for reading characters. BufferedReader wraps it and supplies readLine. A method accepting a Reader can be tested with a string instead of opening a real file. That is the same dependency-boundary idea as intermediate's formatter interface, now applied to a standard library type.
The caller guarantees a nonnull Reader. The contract here says the caller owns the reader and closes it. Therefore readBounded must not put the supplied reader in its own try-with-resources block. It may wrap it for line access, but ownership stays with the caller. The caller's try block closes the StringReader after use. IOException is declared with throws and handled by the caller rather than mistaken for malformed input.
Count physical lines before filtering blanks; a million blank lines still require work. The limit is checked before adding the next line. A line-count limit does not bound the size of one line: readLine can allocate a very long string. The later capstone takes an already-sized input string with a total-character limit. For hostile streaming inputs, a character-by-character bounded reader would be another requirement.
Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.
import java.io.Reader;
import java.io.StringReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
try (Reader input = new StringReader("A\n\nB\n")) {
System.out.println(readBounded(input, 3).size());
} catch (IOException error) {
throw new IllegalStateException("read failed", error);
}
}
static List<String> readBounded(Reader input, int maximum) throws IOException {
if (maximum < 0) {
throw new IllegalArgumentException("negative limit");
}
BufferedReader reader = new BufferedReader(input);
List<String> lines = new ArrayList<>();
String line = reader.readLine();
while (line != null) {
if (lines.size() == maximum) {
throw new IllegalArgumentException("too many lines");
}
lines.add(line);
line = reader.readLine();
}
return List.copyOf(lines);
}
}Check your prediction
3Trace a different case
A limit of zero permits empty input but no records. A trailing newline terminates the preceding line; it does not create an extra line after EOF. An actual additional blank line does count. These details are part of the boundary contract and are worth predicting before testing. The following example traces the standard reader behavior directly.
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new StringReader("A\n\n"))) {
System.out.println(reader.readLine());
System.out.println(reader.readLine().isEmpty());
System.out.println(reader.readLine() == null);
} catch (IOException error) {
throw new IllegalStateException("read failed", error);
}
}
}Check your prediction
A
true
trueName the resource owner and the unit of every limit
A method accepting a Reader does not necessarily own its lifetime. In this example the caller created it and closes it. If a method opens a file itself, it normally owns that resource and should close it. The type alone does not communicate the complete ownership policy, so document it.
A limit must also name its unit: bytes, UTF-16 String length and physical lines are different measurements. A line limit can still allow an enormous single line. A character check on an already-created String limits later processing but cannot reverse memory allocation that already happened.
Test the inclusive boundary and one step beyond it, with blanks included in physical line counting. Keep input-limit rejection separate from IOException and from a syntactically malformed record; those categories give a caller different information.
Build it yourself
Bounded Readers: practice
Write readNonblank(Reader input, int maximum). It returns the nonblank lines,
trimmed, and throws IllegalArgumentException("too many lines") when the input
has more than maximum physical lines. Blank lines are not returned but still
count against the limit. The caller owns input: your method must not close it.
The workspace already runs four cases with a limit of 3. Predict each result, then implement the method so the output matches this table:
| Input | Expected | What it checks |
|---|---|---|
"A\n\nB\n" | [A, B] | a blank line counts but is not returned |
" A\nB\nC" | [A, B, C] | exactly 3 lines is allowed; no trailing newline |
"\n\n\nA" | Rejected: too many lines | blanks use up the budget |
"" | [] | empty input |
show calls input.ready() after your method returns. On a closed reader it
throws IOException("Stream closed"), so the program itself checks ownership.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
show("A\n\nB\n");
show(" A\nB\nC");
show("\n\n\nA");
show("");
}
static void show(String text) throws IOException {
try (Reader input = new StringReader(text)) {
try {
System.out.println(readNonblank(input, 3));
} catch (IllegalArgumentException rejected) {
System.out.println("Rejected: " + rejected.getMessage());
}
input.ready();
}
}
static List<String> readNonblank(Reader input, int maximum) throws IOException {
// Count every physical line against maximum; keep only nonblank lines, trimmed.
// Do not close input: the caller owns it.
return List.of();
}
}Hint 1: the idea
Two counts are in play: physical lines read, which the limit is about, and lines kept, which the result is about. Use a separate counter for the first; the result list's size would ignore blanks.
Hint 2: a first step
Wrap input in a BufferedReader without try-with-resources, and loop on
readLine() until it returns null. Increment the physical count for every line
before deciding whether to keep it, and check the limit right after.
Show one solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
show("A\n\nB\n");
show(" A\nB\nC");
show("\n\n\nA");
show("");
}
static void show(String text) throws IOException {
try (Reader input = new StringReader(text)) {
try {
System.out.println(readNonblank(input, 3));
} catch (IllegalArgumentException rejected) {
System.out.println("Rejected: " + rejected.getMessage());
}
input.ready();
}
}
static List<String> readNonblank(Reader input, int maximum) throws IOException {
BufferedReader reader = new BufferedReader(input);
List<String> result = new ArrayList<>();
int physical = 0;
String line = reader.readLine();
while (line != null) {
physical++;
if (physical > maximum) {
throw new IllegalArgumentException("too many lines");
}
if (!line.isBlank()) {
result.add(line.trim());
}
line = reader.readLine();
}
return List.copyOf(result);
}
}Expected output:
[A, B]
[A, B, C]
Rejected: too many lines
[]physical counts every line readLine returns, so the third case fails on its
fourth line even though only one would be kept. The check is physical > maximum, which makes the limit inclusive: three lines pass in the second case.
The BufferedReader is not in a try-with-resources block, because closing it
would close the caller's reader too. Put it in one and the first case still
prints [A, B], but input.ready() then throws java.io.IOException: Stream closed.
Change it and test again
A line limit does not bound the size of one line. Write checkSize(String text, int maximum) that returns text when its length() is at most maximum and
otherwise throws IllegalArgumentException; reject null and a negative maximum
too. Check "" at 0, "abc" at 3, and "abcd" at 3. Then explain why checking an
already allocated String limits downstream processing but cannot undo the memory
spent receiving it, and what unit length() measures (UTF-16 code units, not
bytes).
Explain before moving on
Who closes a caller-owned resource? How would that contract change if the method opened its own file? Distinguish input-size rejection, malformed record rejection and IOException; each needs an honest response from the caller.
Completion is saved in this browser only. It does not measure mastery.