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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Records give you a concise, immutable value type that can still carry focused behavior like extract.
- 2Clamping substring bounds with Math.min keeps parsing robust against short or ragged input lines.
- 3A factory method that parses a compact spec keeps the layout definition close to how callers think about columns.
Related explainers
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-fixed-width-text-in-java-explained-java-1013/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.