• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
山高我为峰
博客园    首页    新随笔    联系   管理    订阅  订阅
读取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();

    }
}

 

posted on 2016-06-07 19:50  山高我为峰  阅读(256)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3