【问题标题】:How to read a file to java lists?如何将文件读入java列表?
【发布时间】:2012-03-09 13:02:33
【问题描述】:

我的公司有一个非常奇怪的文件。它是由人们很久以前编写的程序生成的。它包含一堆属性以及拥有这些属性的用户。它看起来像下面。我必须逐行阅读此文件并将属性和用户分成两个列表。例如,在第一行中,所有道具都应该在一个列表中,方括号内的用户应该在另一个列表中。用户数量一直在变化,这让我的任务变得复杂。有人可以建议我破解它吗?我用几个小时而不是它来破解我的头。任何提示都会非常明显。

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

【问题讨论】:

  • 使用方括号来识别用户的列表。顺便说一句,你有没有尝试过任何东西???

标签: java file list


【解决方案1】:

我会编写一个带有状态机的简单解析器,其中[ 将您切换到读取用户,] 将您切换到读取属性。

另一种方法是将行拆分为两种方式。

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
    }
}

【讨论】:

    猜你喜欢
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    相关资源
    最近更新 更多