如何从属性文件中存储特定的键值对

How to store specific Key-Value Pairs from properties file

我想将 config.properties 文件中的键值对存储在 java 中。问题是它有一些其他的不想存储在数组中或者 hashmap.Below 是我的 config.properties 文件。一件事该行必须以 #usergroup 开头,行尾应该是 End_TT_Executive,如文件

中所述
#Usergroup
TT_Executive
#Tilename
KPI
#No of Submenu=3
#Submenu_1
OPs_KPI=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Submenu_2
Ontime_OnBudget=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#submenu_3
Ops_KPI_Cloud=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html

#Tilename
Alerting Dashboard
#No of submenu=0
Alerting_Dashboard=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html

#Tilename
FTE_Dashboard
#No of submenu=3
#Submenu_1
FTE_Market_Sector_TT_Executive= https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html

#submenu_2
FTE_Account_TT_Executive= http://tntanalytics1.sl1430087.sl.dst.ibm.com/ibmcognos/bi/?pathRef=.public_folders%2FP=false
#Submenu_3
FTE_Laborpool_TT_Executive= https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html


#Tilename
PCR
#No of Submenu=0
PCR=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html

End_TT_Executive

我该怎么做?键值对都是带URL的,剩下的就是一些理解题。

假设您的 config.properties 是这样的:

p1=abc
p2=def
p3=zxc
p4=eva

并且您想将 p1 和 p2 加载到映射中。

您可以将所有属性加载到 Properties 实例中:

InputStream inputStream = null;

        try
        {
            inputStream = new BufferedInputStream(new FileInputStream("config.properties"));
            Properties properties = new Properties(); 

            properties.load(new InputStreamReader(inputStream, "UTF-8")); // load all properties in config.properties file
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            inputStream.close();
        }

然后你创建一个地图:

Map<String, String> propertyMap = new HashMap<>();

您还需要一个 String[] 来存储您要加载到 propertyMap 的所有属性。

String[] wantedProperties = new String[]{"p1", "p2"};

然后你写一个for循环来加载你想要的属性:

for (String property : wantedProperties) {
    propertyMap.put(property, properties.getProperty(property));
}

现在propertyMap就是你想要的。

如果要存储到列表:

List<String> propertyList = new ArrayList<>();
for (String property : wantedProperties) {
    propertyList.add(properties.getProperty(property));
}

这是保存到列表的方法。如果您自己找到解决方案,它会帮助您更多。