美文网首页
Java properties工具类

Java properties工具类

作者: 视频怪物 | 来源:发表于2019-12-18 22:36 被阅读0次

目的

  1. 快速生成properties文件
  2. 解析properties文件直接根据key获取对应value

工具类代码

package com.ee2j.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.assertj.core.util.Strings;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

/**
 * properties工具类
 *
 * @author videomonster
 * @since 1.0.0
 */
@Slf4j
public class PropertiesUtils {

    /**
     * 创建properties文件
     *
     * @param filePath
     * @param properties
     * @throws IOException
     */
    public static void store(String filePath, Map<String, String> properties) throws IOException {
        if (Strings.isNullOrEmpty(filePath) || MapUtils.isEmpty(properties)) {
            log.error("filePath or properties isNullOrEmpty");
            return;
        }
        Properties p = new Properties();
        try (FileWriter fw = new FileWriter(filePath)) {
            for (String key : properties.keySet()) {
                p.setProperty(key, properties.get(key));
            }
            p.store(fw, "");
        }

    }

    /**
     * 查询指定的value
     * @param filePath
     * @param key
     * @return
     */
    public static String get(String filePath, String key) throws IOException {
        if (Strings.isNullOrEmpty(filePath) || Strings.isNullOrEmpty(key)) {
            log.error("filePath or key isNullOrEmpty");
            return "";
        }
        try (FileReader fr = new FileReader(filePath)) {
            Properties p = new Properties();
            p.load(fr);
            return p.getProperty(key);
        }
    }
}

测试用例

package com.ee2j.utils;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.util.Assert;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PropertiesUtilTest {

    private String filePath = "./test.properties";

    private Map<String, String> propMap = new HashMap<>(16);

    private void deleteFile() {
        File file = new File(filePath);
        file.deleteOnExit();
    }

    @Before
    public void init() {
        propMap.put("no", "zlg00011");
        propMap.put("name", "雨花台巡逻指令官X-11");
    }

    @Test
    public void store() throws IOException {
        deleteFile();
        PropertiesUtils.store(filePath, propMap);
        File file = new File(filePath);
        Assert.isTrue(file.exists(), "");
    }

    @Test
    public void get() throws IOException {
        deleteFile();
        // 生成文件
        PropertiesUtil.store(filePath, propMap);
        String no = PropertiesUtils.get(filePath, "no");
        Assert.isTrue(propMap.get("no").equals(no), "");
    }

    @After
    public void after() {
        deleteFile();
    }
}

相关文章

网友评论

      本文标题:Java properties工具类

      本文链接:https://www.haomeiwen.com/subject/dgjpnctx.html