开发者

Whats the best way to parse a file in Java

I have a text file with Tag - Value format data. I want to parse this file to form a Trie. What will be the best approach?

Sample of File: (String inside "" is a tag and '#' is used to comment the line.)

 #Hi, this is a开发者_Go百科 sample file.

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


This is basically a properties file, I would remove the " around the tags, then use the Properties class http://java.sun.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader) to load the file.


Read that in using Properties and trim the excess parts (", ; and whitespace). Short example:

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()));
}

Note that in the solution above you only need implement the cleanKey() and cleanValue() yourself. You may want to change the datatypes accordingly if necessary, I used Strings just as an example.


There are many ways to do this; others have mentioned that java.util.Properties gets most of the job done, and is probably the most robust solution.

One other option is to use a java.util.Scanner.

  • Use the Scanner(File) constructor to scan a file
  • You can useDelimiter appropriate for this format
  • nextInt() can be used to extract the numbers
  • Perhaps you can put the key/value pairs into a SortedMap<String,Integer>

Here's an example that scans a String for simplicity:

    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);

This prints (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}

Related questions

  • Validating input using java.util.Scanner
  • Iterate Over Map

See also

  • regular-expressions.info/Tutorial


The most natural way is probably this:

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);
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜