properties配置文件操作工具类

properties配置文件操作工具类

package com.util;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * 对properties配置文件进行增删改查操作
 * Created by 张勇波 on 2016/8/18.
 */
public class PropertiesUtil {
    public static void main(String[] args) {
        //PropertiesUtil pu = new PropertiesUtil("", false);
        PropertiesUtil pu = new PropertiesUtil("superUser.properties", false);
        //File f = new File(pu.getClass().getResource("/").getPath());
        //System.out.println(f);
        pu.setProperties("systemdev", "zhangyongbo");
        //pu.delProperties("systemdev");
        Map<String, String> map = pu.readAllProperties();
        for (String s : map.keySet()) {
            System.out.println(s + " " + map.get(s));
        }
    }

    /**
     * 配置文件对象
     */
    private static Properties props = null;

    /**
     * 配置文件物理路径
     */
    private String filePath = "";

    /**
     * 获取classes下配置文件信息
     * 如果配置文件不存在则创建一个空文件
     * bool为false且HttpServletRequest有参数传入时根据request.getSession().getServletContext().getContextPath()获取路径
     * 因为web项目下getResource("/").getPath()获取路径不准确
     *
     * @param fileName 配置文件名称
     * @param bool     是否绝对路径.true是,fileName为配置文件物理路径。否则取classes路径,fileName为配置文件名称。
     * @param request  HttpServletRequest
     */
    public PropertiesUtil(String fileName, boolean bool, HttpServletRequest request) {
        if (!bool) {
            if (request != null) {
                filePath = request.getSession().getServletContext().getRealPath("/") + "WEB-INF/classes/" + fileName;
            } else {
                filePath = new File(PropertiesUtil.class.getResource("/").getPath()) + "/" + fileName;
                //filePath = new File(PropertiesUtil.class.getClassLoader().getResource("").getPath()) + "/" + fileName;
                //filePath = new File(Thread.currentThread().getContextClassLoader().getResource("").getPath()) + "/" + fileName;
            }
        } else {
            filePath = fileName;
        }
        getProps(filePath);
    }

    /**
     * 获取classes下配置文件信息
     * 如果配置文件不存在则创建一个空文件
     * java项目(非web项目建议使用此项)
     *
     * @param fileName 配置文件名称
     * @param bool     是否绝对路径.true是,fileName为配置文件物理路径。否则取classes路径,fileName为配置文件名称。
     */
    public PropertiesUtil(String fileName, boolean bool) {
        if (!bool) {
            filePath = new File(PropertiesUtil.class.getResource("/").getPath()) + "/" + fileName;
        } else {
            filePath = fileName;
        }
        getProps(filePath);
    }

    /**
     * 获取classes下配置文件信息
     * 如果配置文件不存在则创建一个空文件
     * web系统建议使用此项
     *
     * @param fileName 配置文件名称
     * @param request  HttpServletRequest
     */
    public PropertiesUtil(String fileName, HttpServletRequest request) {
        if (request != null) {
            filePath = request.getSession().getServletContext().getRealPath("/") + "WEB-INF/classes/" + fileName;
        } else {
            filePath = new File(PropertiesUtil.class.getResource("/").getPath()) + "/" + fileName;
        }
        getProps(filePath);
    }

    private void getProps(String filePath) {
        props = new Properties();
        try {
            File myFile = new File(filePath);
            if (!myFile.exists())
                myFile.createNewFile();
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            props.load(in);
            // 关闭资源
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据key值读取配置的值
     *
     * @param key key值
     * @return key键对应的值
     */
    public String readValue(String key) {
        return props.getProperty(key);
    }

    /**
     * 更新(插入)一对配置
     *
     * @param key   key值
     * @param value value值
     */
    public void setProperties(String key, String value) {
        if (key != null && value != null && key.length() > 0) {
            try {
                OutputStream fos = new FileOutputStream(filePath);
                props.setProperty(key, value);
                props.store(fos, "Update:'" + key + "'value");
            } catch (IOException ignored) {
                ignored.printStackTrace();
            }
        }
    }

    /**
     * 删除一对配置
     *
     * @param key key值
     */
    public void delProperties(String key) {
        if (key != null && key.length() > 0) {
            Map<String, String> map = readAllProperties();
            Properties p = new Properties();
            String val = "";
            for (String s : map.keySet()) {
                if (s.equals(key)) {
                    val = map.get(s);
                    continue;
                }
                p.setProperty(s, map.get(s));
            }
            try {
                FileWriter writer = new FileWriter(filePath);
                p.store(writer, "delete:'" + key + "'value'" + val + "'");
            } catch (IOException ignored) {
                ignored.printStackTrace();
            }
            props = p;
        }
    }

    /**
     * 读取properties的全部信息
     *
     * @return "Map<String, String>"结构结果集
     */
    public Map<String, String> readAllProperties() {
        // 保存所有的键值
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<?> en = props.propertyNames();
        while (en.hasMoreElements()) {
            String key = (String) en.nextElement();
            String Property = props.getProperty(key);
            map.put(key, Property);
        }
        return map;
    }

    /**
     * 得到某一个类的路径
     *
     * @param aClass 类
     * @return 类物理地址
     */
    private String getPath(Class<PropertiesUtil> aClass) {
        String strResult;
        if (System.getProperty("os.name").toLowerCase().contains("window")) {
            strResult = aClass.getResource("/").toString().replace("file:/", "").replace("%20", " ");
        } else {
            strResult = aClass.getResource("/").toString().replace("file:", "").replace("%20", " ");
        }
        return strResult;
    }
}

 上一篇
okhttp3检测url okhttp3检测url
okhttp3检测urlimport okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; impor
2019-08-19
下一篇 
slf4j介绍 slf4j介绍
slf4j介绍slf4j全称是:simple logging facade for java,可以理解为简单日记门面。准确的说,slf4j并不是一种具体的日志系统,而是一个用户日志系统的facade,它允许用户在部署最终应用时方便的变更其日
2019-08-19
  目录