实现说明
活动部件是类 FixedWidthLog、Column和函数 main。
for (String line : lines) 反复执行,循环体之外没有别的重复。
使用要点
- 演示输出是带标签的(
--),每个操作都会留下自己的一行标注。
常见问题
运行「解析定宽列文本」会打印什么?
整个文件跑完,输出行以 -- 这类前缀开头。
核心语句
return line.length() <= start ? "" : line.substring(start, Math.min(end, line.length()));
代码示例
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("--");
}
}
}