java 44 lines · 7 steps

Parsing fixed-width text in Java

A record plus a small parser turn column ranges into named field maps, one line at a time.

Explained by highlit
1public record FixedWidthField(String name, int start, int end) {
2 
3 public String extract(String line) {
4 int from = Math.min(start, line.length());
5 int to = Math.min(end, line.length());
6 return line.substring(from, to).trim();
7 }
8}
9 
10class FixedWidthParser {
11 
12 private final List<FixedWidthField> layout;
13 
14 FixedWidthParser(List<FixedWidthField> layout) {
15 this.layout = List.copyOf(layout);
16 }
17 
18 Map<String, String> parse(String line) {
19 Map<String, String> record = new LinkedHashMap<>();
20 for (FixedWidthField field : layout) {
21 record.put(field.name(), field.extract(line));
22 }
23 return record;
24 }
25 
26 List<Map<String, String>> parseAll(Stream<String> lines) {
27 return lines
28 .filter(line -> !line.isBlank())
29 .map(this::parse)
30 .collect(Collectors.toList());
31 }
32 
33 static FixedWidthParser fromDefinition(String... columns) {
34 List<FixedWidthField> fields = new ArrayList<>();
35 for (String column : columns) {
36 String[] parts = column.split(":");
37 String name = parts[0].trim();
38 int start = Integer.parseInt(parts[1].trim());
39 int width = Integer.parseInt(parts[2].trim());
40 fields.add(new FixedWidthField(name, start, start + width));
41 }
42 return new FixedWidthParser(fields);
43 }
44}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Records give you a concise, immutable value type that can still carry focused behavior like extract.
  2. 2Clamping substring bounds with Math.min keeps parsing robust against short or ragged input lines.
  3. 3A factory method that parses a compact spec keeps the layout definition close to how callers think about columns.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing fixed-width text in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code