什么是用Java解析文件的最佳方法

时间:2010-06-17 20:25:04

标签: java

我有一个带有Tag - Value格式数据的文本文件。我想解析这个文件以形成一个Trie。什么是最好的方法?

文件样本:(“”里面的字符串是标签,'#'用来评论该行。)

 #Hi, this is a sample file.

"abcd" = 12;
"abcde" = 16;
"http" = 32;
"sip" = 21;

4 个答案:

答案 0 :(得分:5)

使用Properties阅读并修剪多余的部分(";和空格)。简短的例子:

Properties props = Properties.load(this.getClass()
                                       .getResourceAsStream("path/to.file"));
Map<String, String> cleanedProps = new HashMap<String, String>();
for(Entry pair : props.entrySet()) {
    cleanedProps.put(cleanKey(pair.getKey()),
                     cleanValue(pair.getValue()));
}

请注意,在上述解决方案中,您只需自己实施cleanKey()cleanValue()。如果需要,您可能需要相应地更改数据类型,我只使用字符串作为示例。

答案 1 :(得分:5)

这基本上是一个属性文件,我会删除“围绕标签,然后使用属性类http://java.sun.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader)来加载文件。

答案 2 :(得分:1)

有很多方法可以做到这一点;其他人提到java.util.Properties完成了大部分工作,可能是最强大的解决方案。

另一个选择是使用java.util.Scanner

以下是一个简单扫描String的示例:

    String text =
        "#Hi, this is a sample file.\n" +
        "\n" +
        "\"abcd\" = 12; \r\n" +
        "\"abcde\"=16;\n" + 
        "  # \"ignore\" = 13;\n" +
        "\"http\" = 32;  # Comment here \r" + 
        "\"zzz\" = 666;  # Out of order! \r" + 
        "   \"sip\"  =  21 ;";

    System.out.println(text);
    System.out.println("----------");

    SortedMap<String,Integer> map = new TreeMap<String,Integer>();
    Scanner sc = new Scanner(text).useDelimiter("[\"=; ]+");
    while (sc.hasNextLine()) {
        if (sc.hasNext("[a-z]+")) {
            map.put(sc.next(), sc.nextInt());
        }
        sc.nextLine();
    }
    System.out.println(map);

打印(as seen on ideone.com):

#Hi, this is a sample file.

"abcd" = 12; 
"abcde"=16;
  # "ignore" = 13;
"http" = 32;  # Comment here 
"zzz" = 666;  # Out of order! 
   "sip"  =  21 ;
----------
{abcd=12, abcde=16, http=32, sip=21, zzz=666}

相关问题

另见

答案 3 :(得分:0)

最自然的方式可能就是:

void doParse() {
        String text =
                "#Hi, this is a sample file.\n"
                + "\"abcd\" = 12;\n"
                + "\"abcde\" = 16;\n"
                + "#More comment\n"
                + "\"http\" = 32;\n"
                + "\"sip\" = 21;";

        Matcher matcher = Pattern.compile("\"(.+)\" = ([0-9]+)").matcher(text);
        while (matcher.find()) {
            String txt = matcher.group(1);
            int val = Integer.parseInt(matcher.group(2));
            System.out.format("parsed: %s , %d%n", txt, val);
        }
    }
相关问题