读取Properties文件工具类

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.struts2.ServletActionContext;


public final class ReadConfigFileUtil {

    private static Properties props = new Properties();

    /* 在类初始化的时候加载配置文件 */
    static {
        // 1.读取配置文件
        InputStream ins = ReadConfigFileUtil.class.getClassLoader().getResourceAsStream("config.properties");
        try {
            // 2.加载配置文件
            props.load(ins);
        } catch (Exception e) {
            throw new RuntimeException(e + "【加载配置文件失败】");
        } finally {
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 根据给定的key键,读取器对应的值value
     * 
     * @param key
     * @return value
     */
    public static String getValue(String key) {
        try {
            return props.getProperty(key) != null ? props.getProperty(key) : "";
        } catch (Exception e) {
            throw new RuntimeException(e + "读取属性【" + key + "】失败");
        }
    }

    /**
     * 根据指定的
     * 
     * @param key
     * @param value
     */
    public static void setValue(String key, String value) {
        try {
            props.setProperty(key, value);
        } catch (Exception e) {
            throw new RuntimeException(e + "为属性【" + key + "】,写入【" + value + "】失败");
        }
    }

    /**
     * 保存修改
     * 
     * @throws IOException
     */
    public static void saveFile() throws IOException {
        String path = ServletActionContext.getServletContext().getRealPath("/WEB-INF/classes/");
        path += "\config.properties";
        FileOutputStream outputStream = new FileOutputStream(path);
        props.store(outputStream, "配置文件");
        outputStream.close();

    }
}
原文地址:https://www.cnblogs.com/liaojie970/p/5568160.html