读取文件并获取 key=value 而不使用 java.util.Properties

发布于 2025-01-05 23:13:40 字数 459 浏览 1 评论 0原文

我正在构建一个 RMI 游戏,客户端将加载一个包含一些键和值的文件,这些键和值将用于多个不同的对象。它是一个保存游戏文件,但我不能为此使用 java.util.Properties (它符合规范)。我必须阅读整个文件并忽略注释行和与某些类不相关的键。这些属性是唯一的,但它们可以按任何顺序排序。我的文件当前文件如下所示:

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

这些属性将根据玩家的进度写入和放置,文件读取器必须到达文件末尾并仅获取匹配的键。我尝试了不同的方法,但到目前为止,没有任何方法可以接近我使用 java.util.Properties 得到的结果。有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

半边脸i 2025-01-12 23:13:40

这将逐行读取“属性”文件并解析每个输入行并将值放入键/值映射中。映射中的每个键都是唯一的(不允许有重复的键)。

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

输出如下所示:

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

您可以使用 map.get("key string"); 访问地图的每个元素。

编辑:此代码不会检查格式错误或丢失的“=”字符串。您可以通过检查对数组的大小在 split 返回时自行添加该内容。

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.

热情消退 2025-01-12 23:13:40

我目前无法想出一个能够提供这一点的框架(尽管我确信有很多),但是,您应该能够自己做到这一点。

基本上,您只需逐行读取文件并检查第一个非空白字符是否是散列(#)或该行是否仅是空白。您可以忽略这些行并尝试在 = 上拆分其他行。如果对于这样的分割,您没有得到 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.

兮子 2025-01-12 23:13:40

或者,您可以使用正则表达式来获取键/值对。

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

将返回每个键及其值的捕获组,并将忽略注释行。

编辑:

这可以变得更简单一些:

[^#]([\w]+)=([\w]+)

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]+)
大姐,你呐 2025-01-12 23:13:40

经过一番研究,我想出了这个解决方案:

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

我正在使用这段代码来检查属性。当然,使用 Properties 库会更明智,但不幸的是我不能。

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.

深海不蓝 2025-01-12 23:13:40

更短的方法如何做到这一点:

    Properties properties = new Properties();
    String confPath = "src/main/resources/.env";
    
    try {
        properties.load(new FileInputStream(confPath));
    } catch (IOException e) {
        e.printStackTrace();
    }

    String specificValueByKey = properties.getProperty("KEY");
    Set<Object> allKeys = properties.keySet();
    Collection<Object> values = properties.values();

The shorter way how to do that:

    Properties properties = new Properties();
    String confPath = "src/main/resources/.env";
    
    try {
        properties.load(new FileInputStream(confPath));
    } catch (IOException e) {
        e.printStackTrace();
    }

    String specificValueByKey = properties.getProperty("KEY");
    Set<Object> allKeys = properties.keySet();
    Collection<Object> values = properties.values();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文