Java properties配置文件工具类

package com.hcs.util;

import javassist.bytecode.stackmap.TypeData;
import org.springframework.util.Assert;

import java.io.*;
import java.net.URL;
import java.util.Properties;
import java.util.Set;

/**
 * properties工具类
 *
 * @author lwt
 * @date 2018/07/25
 * @since 0.1.0
 */
public class ConfigUtils {
    public static String getProperties(String fileName, String key) {
        Properties properties = getProperties(fileName);
        return properties == null ? null : properties.getProperty(key);
    }

    public static Properties getProperties(String path) {
        URL resource = TypeData.ClassName.class.getClassLoader().getResource(path);
        Assert.notNull(resource);
        path = resource.getPath();
        Properties properties = new Properties();
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
            properties.load(bufferedReader);
        } catch (Exception e) {
            return null;
        }
        Assert.notNull(properties);
        return properties;
    }

    /**
     * 将Properties持久化到文件
     */
    public static void stormToProperties(Properties p, String path) {
        URL resource = TypeData.ClassName.class.getClassLoader().getResource(path);
        Assert.notNull(resource);
        path = resource.getPath();
        try {
            PrintStream fW = null;
            try {
                fW = new PrintStream(new FileOutputStream(path), true, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            Assert.notNull(fW);
            p.list(fW);
            fW.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

猜你喜欢

转载自blog.csdn.net/u013767488/article/details/81200513