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 Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 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.