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

时间:2018-08-01 07:47:12

标签: java config

我想将config.properties文件中的键值对存储在java中。问题是它还有其他不想存储在数组或哈希图中的东西。下面是我的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的键值对是一些易于理解的标题。

1 个答案:

答案 0 :(得分:0)

假设您的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));
}

这是保存到列表的方式。如果您自己找到解决方案,它将为您提供更多帮助。