Read file and get key=value without using java.util.Properties

北城余情 提交于 2019-12-05 19:16:45

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.

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.

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]+)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!