Parse Fixed Width Column Text
Extract fields from fixed-width records with per-column start and end offsets, keeping short lines honest instead of throwing past the line end.
Code
import java.util.List;
public class FixedWidthLog {
// 固定宽度记录(fixed width):每列的起止由偏移约定,不靠分隔符切分
record Column(String name, int start, int end) {
String extract(String line) {
return line.length() <= start ? "" : line.substring(start, Math.min(end, line.length()));
}
}
static final List<Column> LAYOUT = List.of(
new Column("sensor", 0, 8),
new Column("value", 8, 16),
new Column("unit", 16, 24));
public static void main(String[] args) {
List<String> lines = List.of(
"boiler- 83.25 celsius ",
"pump-2 4.00 bar ",
"short");
for (String line : lines) {
for (Column column : LAYOUT) {
System.out.println(column.name() + "=[" + column.extract(line).strip() + "]");
}
System.out.println("--");
}
}
}Following the data
The moving parts are the classes FixedWidthLog and Column and the function main.
for (String line : lines) does the per-item lifting.
What to watch for
- The toolchain covers it — nothing to resolve, nothing to fetch.
Using it
Entry signature: public static void main(String[] args)
The run tags its output — -- — when the file runs.
Key statements
return line.length() <= start ? "" : line.substring(start, Math.min(end, line.length()));
Interactive Tools for This Topic
CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Parse Fixed Width Column Text print when run?
- Execute the whole file; each printed line is prefixed with a label like `--`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.