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.

JavaCli Tooling

Code

snippet
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

FAQ

What does Parse Fixed Width Column Text print when run?
Execute the whole file; each printed line is prefixed with a label like `--`.