基于Java的Properties文件解析

Properties文件:
username = 111222333
memorableAnswer = aaabbb
password = cccddd
代码(方法一):
package com.utils;

import org.junit.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class FileParseProperties {

    public static final String PROPERTY_FILE_PATH = "src/test/resources/UserProfiles/111222333.properties";

    @Test
    public void getProperties(){
        Map<String, String> ss;
        ss = readProperties(PROPERTY_FILE_PATH);
        System.out.println(ss);
        Set keys = ss.keySet();
        for(Object key : keys){
            System.out.println(key + ":" + ss.get(key));
        }
    }

    public Map<String, String> readProperties(String path){
        Properties properties = new Properties();
        Map<String, String> propMap =  new HashMap<>();
        try{
            InputStream inputStream = new FileInputStream(path);
            Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            properties.load(reader);
        }catch(Exception e){
            e.printStackTrace();
        }
        for(Map.Entry<Object,Object> entries : properties.entrySet()){
            propMap.put((String)entries.getKey(),(String)entries.getValue());
        }
        return  propMap;
    }
}
代码(方法二):
public class FileParseProperties {

    public static final String PROPERTY_FILE_PATH = "src/test/resources/UserProfiles/111222333.properties";

    @Test
    public void getProperties(){
        Properties ss;
        ss = readAndReturnProperties(PROPERTY_FILE_PATH);
        System.out.println(ss);
        Set keys = ss.keySet();
        for(Object key : keys){
            System.out.println(key + ":" + ss.get(key));
        }
    }

    private Properties readAndReturnProperties(String path) {
        Properties prop = new Properties();
        InputStream input = null;
        try{
            input =  new FileInputStream(path);
            prop.load(input);
        }catch(IOException e){
            e.printStackTrace();
        }
        return prop;
    }
}
运行结果:
{password=cccddd, memorableAnswer=aaabbb, username=111222333}
password:cccddd
memorableAnswer:aaabbb
username:111222333
posted @ 2021-04-17 01:25  meiyouyou  阅读(122)  评论(0编辑  收藏  举报