3

I'm building a RMI game and the client would load a file that has some keys and values which are going to be used on several different objects. It is a save game file but I can't use java.util.Properties for this (it is under the specification). I have to read the entire file and ignore commented lines and the keys that are not relevant in some classes. These properties are unique but they may be sorted in any order. My file current file looks like this:

# Bio
playerOrigin=Newlands
playerClass=Warlock
# Armor
playerHelmet=empty
playerUpperArmor=armor900
playerBottomArmor=armor457
playerBoots=boot109
etc

These properties are going to be written and placed according to the player's progress and the filereader would have to reach the end of file and get only the matched keys. I've tried different approaches but so far nothing came close to the results that I would had using java.util.Properties. Any idea?

Samuel Guimarães
  • 554
  • 3
  • 6
  • 18

4 Answers4

5

This will read your "properties" file line by line and parse each input line and place the values in a key/value map. Each key in the map is unique (duplicate keys are not allowed).

package samples;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.TreeMap;

public class ReadProperties {

    public static void main(String[] args) {
        try {
           TreeMap<String, String> map = getProperties("./sample.properties");
           System.out.println(map);
        }
        catch (IOException e) {
            // error using the file
        }
    }

    public static TreeMap<String, String> getProperties(String infile) throws IOException {
        final int lhs = 0;
        final int rhs = 1;

        TreeMap<String, String> map = new TreeMap<String, String>();
        BufferedReader  bfr = new BufferedReader(new FileReader(new File(infile)));

        String line;
        while ((line = bfr.readLine()) != null) {
            if (!line.startsWith("#") && !line.isEmpty()) {
                String[] pair = line.trim().split("=");
                map.put(pair[lhs].trim(), pair[rhs].trim());
            }
        }

        bfr.close();

        return(map);
    }
}

The output looks like:

{playerBoots=boot109, playerBottomArmor=armor457, playerClass=Warlock, playerHelmet=empty, playerOrigin=Newlands, playerUpperArmor=armor900}

You access each element of the map with map.get("key string");.

EDIT: this code doesn't check for a malformed or missing "=" string. You could add that yourself on the return from split by checking the size of the pair array.

jmq
  • 9,602
  • 14
  • 54
  • 68
2

I 'm currently unable to come up with a framework that would just provide that (I'm sure there are plenty though), however, you should be able to do that yourself.

Basically you just read the file line by line and check whether the first non whitespace character is a hash (#) or whether the line is whitespace only. You'd ignore those lines and try to split the others on =. If for such a split you don't get an array of 2 strings you have a malformed entry and handle that accordingly. Otherwise the first array element is your key and the second is your value.

Thomas
  • 80,843
  • 12
  • 111
  • 143
1

Alternately, you could use a regular expression to get the key/value pairs.

(?m)^[^#]([\w]+)=([\w]+)$

will return capture groups for each key and its value, and will ignore comment lines.

EDIT:

This can be made a bit simpler:

[^#]([\w]+)=([\w]+)
Tony
  • 1,311
  • 8
  • 11
  • You'd need to make the `[^#]` into an assertion, otherwise on non-commented lines that will capture the first character of the line. – nickb Jul 26 '13 at 15:04
1

After some study i came up with this solution:

public static String[] getUserIdentification(File file) throws IOException {
        String key[] = new String[3];
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String lines;
        try {
            while ((lines = br.readLine()) != null) {
                String[] value = lines.split("=");
                if (lines.startsWith("domain=") && key[0] == null) {
                    if (value.length <= 1) {
                        throw new IOException(
                                "Missing domain information");
                    } else {
                        key[0] = value[1];
                    }
                }

                if (lines.startsWith("user=") && key[1] == null) {
                    if (value.length <= 1) {
                        throw new IOException("Missing user information");
                    } else {
                        key[1] = value[1];
                    }
                }

                if (lines.startsWith("password=") && key[2] == null) {
                    if (value.length <= 1) {
                        throw new IOException("Missing password information");
                    } else {
                        key[2] = value[1];
                    }
                } else
                    continue;
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return key;
}

I'm using this piece of code to check the properties. Of course it would be wiser to use Properties library but unfortunately I can't.

Samuel Guimarães
  • 554
  • 3
  • 6
  • 18