我有一个包含以下矩阵/表格的文本文件:
# Matrix size is 13x13
DEPOT CHESHNT LIVST CHINGFD ENFLDTN HERTFDE BSHPSFD CAMBDGE STFD ELYY KLYNN STANAIR BROXBRN
DEPOT 00:00 01:00 00:28 00:02 00:40 01:00 00:02 00:05 01:00 00:30 01:00 00:31 01:00
CHESHNT 01:00 00:00 00:38 01:00 01:03 01:27 01:02 01:05 01:56 01:21 02:00 01:25 02:00
LIVST 00:28 00:38 00:00 00:22 00:25 00:49 01:00 01:27 01:20 01:44 01:24 00:47 01:24
CHINGFD 00:02 01:00 00:20 00:00 00:42 01:02 00:45 01:30 00:58 01:45 01:30 00:45 01:02
ENFLDTN 00:40 01:03 00:25 00:42 00:00 01:14 00:42 00:45 01:36 01:01 01:40 01:11 01:40
HERTFDE 01:00 01:27 00:49 01:02 01:14 00:00 01:02 01:05 00:56 01:21 02:00 01:31 01:26
BSHPSFD 00:02 01:02 01:00 01:00 00:42 01:02 00:00 00:30 00:54 00:47 01:02 00:33 01:02
CAMBDGE 00:03 01:05 01:27 01:30 00:45 01:05 00:30 00:00 01:01 00:17 01:05 00:36 01:05
STFD 01:00 01:56 01:20 00:58 01:36 00:52 00:54 01:01 00:00 01:17 01:56 01:06 00:30
ELYY 00:22 01:30 01:44 01:45 01:10 01:30 00:47 00:17 01:26 00:00 01:30 01:01 01:30
KLYNN 00:52 02:00 01:24 01:30 01:40 02:00 01:02 01:05 01:56 01:21 00:00 01:31 02:00
STANAIR 00:31 01:12 00:36 00:45 00:52 01:12 00:33 00:36 01:02 00:53 01:12 00:00 01:12
BROXBRN 01:00 02:00 01:24 01:02 01:40 01:23 01:02 01:05 00:31 01:21 02:00 01:31 00:00
鉴于结构很常见,是否没有Java库可以解析为Java结构? 类似的东西:
Map<String,String> matrix = MatrixParser.parse("matrix.txt"); //where the key is the concatenation of the row and column coordinates.
我可以看到使用OpenCSV将其解析为CSV,分隔符是空格或制表符而不是逗号。没什么更高的水平?
答案 0 :(得分:1)
来自常见问题:
ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
strat.setType(YourOrderBean.class);
String[] columns = new String[] {"name", "orderNumber", "id"}; // the fields to bind do in your JavaBean
strat.setColumnMapping(columns);
CsvToBean csv = new CsvToBean();
List list = csv.parse(strat, yourReader);
那就是说,反正并不难:)
在逐行拆分之后,您可以使用Commons BeanUtils' populate()
method在几行代码中执行相同的操作。伪代码:
cols = loadColumnNamesToArray();
while (moreLines()) {
vals = line.split
vals.each_with_index {
colName = cols[index]
valMap.put(colName, val)
}
bean = Bean.new
BeanUtils.populate(bean, valMap)
beanList.add(bean)
}