我的公司里有一个非常奇怪的文件。它是由很久以前人们编写的程序生成的。它包含一堆属性以及拥有该属性的用户。看起来像下面这样。我必须逐行读取该文件并将属性和用户分成两个列表。例如,在第一行中,所有 Prop 应位于一个列表中,方括号内的用户应位于另一个列表中。用户数量一直在变化,这使我的任务变得复杂。有人可以建议我破解它吗?我花了几个小时才把头开裂,而不是它。任何提示都将非常值得赞赏。
Properties,prop1,prop2,prop3,[user1,user2,user3,],prop4,prop5
Properties,prop1,prop2,prop3,[user1,user2,user3,user4,],prop4,prop5
Properties,prop1,prop2,prop3,[user1,],prop4,prop5
Properties,prop1,prop2,prop3,[user1,user2,],prop4,prop5
Properties,prop1,prop2,prop3,[user1,user2,user3,user4,user5,],prop4,prop5
最佳答案
我会编写一个带有状态机的简单解析器,其中 [
将您切换为读取用户,]
将您切换为读取属性。
另一种方法是将行分成两种方式。
String line;
while((line = bufferedReader.readLine()) != null) {
for(String parts: line.split("\\[")) {
String[] userProps = parts.split("\\)");
String users = userProps.length==1 ? "" : userProps[0];
String props = userProps[userProps.length-1];
// break up the individual users and props
}
}
关于java - 如何读取文件到java列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9339950/