我的程序将逐行读取文件,然后通过分隔符|分割行(垂直线)并存储到String []中。但是,由于行中的列位置和列数将来会发生变化,而不是使用具体的索引号0,1,2,3 ...,我使用index ++来迭代行拆分令牌;
运行程序后,索引每次增加的次数不是增加1,而是增加1。
我的代码如下:
BufferedReader br = null;
String line = null;
String[] lineTokens = null;
int index = 1;
DataModel dataModel = new DataModel();
try {
br = new BufferedReader(new FileReader(filePath));
while((line = br.readLine()) != null) {
// check Group C only
if(line.contains("CCC")) {
lineTokens = line.split("\\|");
dataModel.setGroupID(lineTokens[index++]);
//System.out.println(index); The value of index not equal to 2 here. The value change each running time
dataModel.setGroupName(lineTokens[index++]);
//System.out.println(index);
// dataModel.setOthers(lineTokens[index++]); <- if the file add columns in the middle of the line in the future, this is required.
dataModel.setMemberID(lineTokens[index++]);
dataModel.setMemberName(lineTokens[index++]);
dataModel.setXXX(lineTokens[index++]);
dataModel.setYYY(lineTokens[index++]);
index = 1;
//blah blah below
}
}
br.close();
} catch (Exception ex) {
}
文件格式如下:
Prefix | Group ID | Group Name | Memeber ID | Member Name | XXX | YYY GroupInterface | AAA | Group A | 001 | Amy | XXX | YYY GroupInterface | BBB | Group B | 002 | Tom | XXX | YYY GroupInterface | AAA | Group A | 003 | Peter | XXX | YYY GroupInterface | CCC | Group C | 004 | Sam | XXX | YYY GroupInterface | CCC | Group C | 005 | Susan | XXX | YYY GroupInterface | DDD | Group D | 006 | Parker| XXX | YYY
而不是增加1,索引++将增加超过1.我想知道为什么会发生这种情况以及如何解决它?任何帮助都非常感谢。
答案 0 :(得分:0)
嗯,@ SomeProgrammerDude狡猾地暗示了它,但我会说出来:当你重置index
时,它应该设置为零,而不是1. / p>
通过在{1}处开始index
,您总是会在您应该到达的位置之前将一个位置编入索引,并且您最终可能会得到一个IndexOutOfBoundsException
被空的catch
条款吞没了。