图书馆的作者在这里。首先,您需要定义字段位置。当您要解析出现在多行中的值时,您必须设置recordEndsOnNewLine
为false
,因此您走在正确的轨道上。
如果您加入形成单个记录的行,则更容易“查看”每条记录的开始和结束位置:
String input = "" +
"AA1234 data\nBBmore data\nCCsome more data row 1 ended\n" +
"AA5678 data\nBBmore data\nCCsome more data row 2 ended";
鉴于您提供的示例,可以创建以下字段配置(我假设您不想要“AA”、“BB”和“CC”字符串):
FixedWidthFields fields = new FixedWidthFields();
fields
.addField("a1", 2, 6)
.addField("a2", 7, 11)
.addField("b1", 14, 23)
.addField("c1", 26, 40)
.addField("c2", 41, 52);
你可以用这个解析你的输入:
FixedWidthParserSettings settings = new FixedWidthParserSettings(fields);
settings.getFormat().setLineSeparator("\n");
settings.setRecordEndsOnNewline(false);
FixedWidthParser parser = new FixedWidthParser(settings);
List<String[]> rows = parser.parseAll(new StringReader(input));
for (String[] row : rows) {
System.out.println(Arrays.toString(row));
}
这将为您提供正确的输出:
[1234, data, more data, some more data, row 1 ended]
[5678, data, more data, some more data, row 2 ended]
现在我们知道每个字段的开始和结束位置,我们可以定义您的 java bean:
public static class Bean {
@FixedWidth(from = 2, to = 6)
@Parsed
int a1;
@FixedWidth(from = 7, to = 11)
@Parsed
String a2;
@FixedWidth(from = 14, to = 23)
@Parsed
String b1;
@FixedWidth(from = 26, to = 40)
@Parsed
String c1;
@FixedWidth(from = 41, to = 52)
@Parsed
String c2;
@Override
public String toString() {
return "Bean{" +
"a1=" + a1 +
", a2='" + a2 + '\'' +
", b1='" + b1 + '\'' +
", c1='" + c1 + '\'' +
", c2='" + c2 + '\'' +
'}';
}
}
准备好之后,解析输入变得很简单:
FixedWidthParserSettings settings = new FixedWidthParserSettings();
settings.getFormat().setLineSeparator("\n");
settings.setRecordEndsOnNewline(false);
settings.setHeaderExtractionEnabled(false); // This one is important as your input has no headers.
FixedWidthRoutines routines = new FixedWidthRoutines(settings);
for(Bean bean : routines.parseAll(Bean.class, new StringReader(input))){
System.out.println(bean);
}
它将像这样将bean打印到输出:
Bean{a1=1234, a2='data', b1='more data', c1='some more data', c2='row 1 ended'}
Bean{a1=5678, a2='data', b1='more data', c1='some more data', c2='row 2 ended'}
希望这可以帮助