如何在Java中创建具有一对多关系的属性?

huangapple go评论59阅读模式
英文:

How create in java a properties with one to many relationship?

问题

我有一个文件,我在文件中保存了一个键和一些条目(一对多关系)。
从这个文件中,我需要通过键提取值。
我刚刚找到了一个工具(java.util.Properties)来处理Java中的属性文件。
它在处理属性文件方面效果非常好。
但是它返回所搜索键的第一个出现的值。
既然在属性文件中存在,我期望已经存在一个允许返回多个结果的版本。

有一种解决方案可以返回一个字符串数组来获取所查询的键吗?

英文:

i have a file where i save one key with some entry (relation one to many).
From this file i need to extract values searching by key.
I just found a util (java.util.Properties) to handle properties files in Java.
It works very well for properties files.
But its return the first occurence for the key searched.
Since is present for properties files i expect that already exist also a version with multiple results allowed.

Exist a solution that returns an array of string for the researched key?

答案1

得分: 1

属性是由Hashtable支持的,因此键必须是唯一的。
因此,如果您想坚持使用相同键的多个实例,可以自己实现解析(如果您不太依赖于属性管理的附加功能):

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class FileInput {
    Properties porp;

    public static Map<String, List<String>> loadProperties(String file) throws IOException {
        HashMap<String, List<String>> multiMap = new HashMap<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line = null;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("#"))
                    continue; // skip comment lines
                String[] parts = line.split("=");
                multiMap.computeIfAbsent(parts[0].trim(), k -> new ArrayList<String>()).add(parts[1].trim());
            }
        }
        return multiMap;
    }

    public static void main(String[] args) throws IOException {
        Map<String, List<String>> result = loadProperties("myproperties.properties");
    }
}

更新:改进了异常处理(感谢 @rzwitsersloot 的有效提醒)。我更喜欢抛出异常,以便调用者可以决定如果属性文件丢失时应该做什么。

英文:

Properties is backed by a Hashtable so the key must be unique.
So if you want to stick to multiple instances of the same key you can implement the parsing yourself (if you don't depend too much on the extras managed by Properties):

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class FileInput {
	Properties porp;

	public static Map&lt;String, List&lt;String&gt;&gt; loadProperties(String file) throws IOException
	{
		HashMap&lt;String, List&lt;String&gt;&gt; multiMap = new HashMap&lt;&gt;();

		try (BufferedReader br = new BufferedReader(new FileReader(file))) {
			String line = null;
			while ((line = br.readLine()) != null) {
				if (line.startsWith(&quot;#&quot;))
					continue; // skip comment lines
				String[] parts = line.split(&quot;=&quot;);
				multiMap.computeIfAbsent(parts[0].trim(), k -&gt; new ArrayList&lt;String&gt;()).add(parts[1].trim());
			}
		}
		return multiMap;
	}
	
	public static void main(String[] args) throws IOException {
		Map&lt;String,List&lt;String&gt;&gt; result=loadProperties(&quot;myproperties.properties&quot;);
	}
}

UPDATED: improved exception handling (valid remark @rzwitsersloot). I prefer to throw the exception so the caller can decide what to do if the properties file is missing.

huangapple
  • 本文由 发表于 2020年10月15日 19:01:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64370132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定