博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Properties文件工具类的使用--获取所有的键值、删除键、更新键等操作
阅读量:6457 次
发布时间:2019-06-23

本文共 13840 字,大约阅读时间需要 46 分钟。

 

  有时候我们希望处理properties文件,properties文件是键值对的文件形式,我们可以借助Properties类操作。

 工具类如下:(代码中日志采用了slf4j日志)

package cn.xm.exam.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Map.Entry;import java.util.Properties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * 操作properties文件的工具类(此工具类的file都是src目录下的properties文件,编译之后在build目录下) *  * @author QiaoLiQiang * @time 2018年11月3日下午12:05:32 */public class PropertiesFileUtils {    private static final Logger log = LoggerFactory.getLogger(PropertiesFileUtils.class);    /**     * 构造函数私有化     */    private PropertiesFileUtils() {    }    /**     * 保存或更新properties文件中的key     *      * @param fileName     * @param key     * @param value     */    public static void saveOrUpdateProperty(String fileName, String key, String value) {        Properties properties = new Properties();        InputStream inputStream;        OutputStream outputStream;        try {            String path = ResourcesUtil.class.getClassLoader().getResource(fileName).getPath();            log.debug("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            properties.setProperty(key, value);            // 保存到文件中(如果有的话会自动更新,没有会创建)            outputStream = new FileOutputStream(new File(path));            properties.store(outputStream, "");            outputStream.close();            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }    }    /**     * 获取Properties     *      * @param fileName     * @param key     * @return     */    public static String getPropertyValue(String fileName, String key) {        Properties properties = new Properties();        InputStream inputStream;        String value = "";        try {            String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();            log.info("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            value = properties.getProperty(key);            // 保存到文件中(如果有的话会自动更新,没有会创建)            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }        return value;    }    /**     * 获取Properties     *      * @param fileName     * @return     */    public static Properties getProperties(String fileName) {        Properties properties = new Properties();        InputStream inputStream;        try {            String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();            log.info("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }        return properties;    }    /**     * 获取Properties     *      * @param fileName     * @return     */    public static Properties removeProperty(String fileName, String key) {        Properties properties = new Properties();        InputStream inputStream;        OutputStream outputStream;        try {            String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();            log.info("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            log.info("properties -> {}", properties);            if (properties != null && properties.containsKey(key)) {                log.info("remove key:{}", key);                properties.remove(key);            }            // 保存到文件中(将properties保存到文件)            outputStream = new FileOutputStream(new File(path));            properties.store(outputStream, "");            outputStream.close();            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }        return properties;    }    public static void main(String[] args) {        // 保存三个 最后一个相当于更新        PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "a", "aaa");        PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "b", "bbb");        PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "c", "ccc");        PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "a", "AAA");        // 获取所有的properties        Properties properties = PropertiesFileUtils.getProperties("settings.properties");        System.out.println(properties);        // 删除a        PropertiesFileUtils.removeProperty("settings.properties", "a");        // 获取所有的properties        Properties properties1 = PropertiesFileUtils.getProperties("settings.properties");        System.out.println(properties1);    }}

 

 

 

结果:

{b=bbb, a=AAA, c=ccc}

{b=bbb, c=ccc}

 

解释:

Properties是继承了HashTable的一个普通类,所以我们可以简单的认为操作Properties就是在操作HashTable。

publicclass Properties extends Hashtable
{ private static final long serialVersionUID = 4112578634029874840L; protected Properties defaults;。。。}

 

 

 由于HasTable键不可以重复,所以我们在saveOrUpdateProperty中直接setProperty的时候如果没有key会创建key,如果key存在会覆盖原来的值。

  properties.load(inputStream);是将properties文件中的key=value的数据加载到properties中;

  properties.store(outputStream, "");是将properties保存到一个文件中。

 

补充:上面代码还可以进一步将properties文件的位置封装全路径:

package cn.xm.exam.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Properties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** *  * @author QiaoLiQiang * @time 2018年11月3日下午12:05:32 */public class PropertiesFileUtils {    private static final Logger log = LoggerFactory.getLogger(PropertiesFileUtils.class);    /**     * 构造函数私有化     */    private PropertiesFileUtils() {    }    /**     * 保存或更新properties文件中的key     *      * @param fileName     * @param key     * @param value     */    public static void saveOrUpdateProperty(String fileName, String key, String value) {        Properties properties = new Properties();        InputStream inputStream;        OutputStream outputStream;        try {            String path = ResourcesUtil.class.getClassLoader().getResource(fileName).getPath();            log.debug("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            properties.setProperty(key, value);            // 保存到文件中(如果有的话会自动更新,没有会创建)            outputStream = new FileOutputStream(new File(path));            properties.store(outputStream, "");            outputStream.close();            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }    }    /**     * 获取Properties     *      * @param fileName     * @param key     * @return     */    public static String getPropertyValue(String fileName, String key) {        Properties properties = new Properties();        InputStream inputStream;        String value = "";        try {            String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();            log.info("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            value = properties.getProperty(key);            // 保存到文件中(如果有的话会自动更新,没有会创建)            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }        return value;    }    /**     * 获取Properties     *      * @param fileName     * @return     */    public static Properties getProperties(String fileName) {        Properties properties = new Properties();        InputStream inputStream;        try {            String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();            log.info("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }        return properties;    }    /**     * 获取Properties     *      * @param fileName     * @return     */    public static Properties removeProperty(String fileName, String key) {        Properties properties = new Properties();        InputStream inputStream;        OutputStream outputStream;        try {            String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();            log.info("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            log.info("properties -> {}", properties);            if (properties != null && properties.containsKey(key)) {                log.info("remove key:{}", key);                properties.remove(key);            }            // 保存到文件中(将properties保存到文件)            outputStream = new FileOutputStream(new File(path));            properties.store(outputStream, "");            outputStream.close();            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }        return properties;    }    /**     * 保存或更新properties文件中的key     *      * @param path     *            文件全路径     * @param key     * @param value     */    public static void saveOrUpdatePropertyByFilePath(String path, String key, String value) {        Properties properties = new Properties();        InputStream inputStream;        OutputStream outputStream;        try {            log.debug("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            properties.setProperty(key, value);            // 保存到文件中(如果有的话会自动更新,没有会创建)            outputStream = new FileOutputStream(new File(path));            properties.store(outputStream, "");            outputStream.close();            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }    }    /**     * 获取Properties     *      * @param path     *            文件全路径     * @param key     * @return     */    public static String getPropertyValueByFilePath(String path, String key) {        Properties properties = new Properties();        InputStream inputStream;        String value = "";        try {            log.info("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            value = properties.getProperty(key);            // 保存到文件中(如果有的话会自动更新,没有会创建)            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }        return value;    }    /**     * 获取Properties     *      * @param path     *            文件全路径     * @return     */    public static Properties getPropertiesByFilePath(String path) {        Properties properties = new Properties();        InputStream inputStream;        try {            log.info("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }        return properties;    }    /**     * 获取Properties     *      * @param path     *            文件全路径     * @param key     *            key值     * @return     */    public static Properties removePropertyByFilePath(String path, String key) {        Properties properties = new Properties();        InputStream inputStream;        OutputStream outputStream;        try {            log.info("path -> {}", path);            inputStream = new FileInputStream(new File(path));            properties.load(inputStream);            log.info("properties -> {}", properties);            if (properties != null && properties.containsKey(key)) {                log.info("remove key:{}", key);                properties.remove(key);            }            // 保存到文件中(将properties保存到文件)            outputStream = new FileOutputStream(new File(path));            properties.store(outputStream, "");            outputStream.close();            inputStream.close();        } catch (FileNotFoundException e) {            log.error("saveOrUpdateProperty error", e);        } catch (IOException e) {            log.error("saveOrUpdateProperty error", e);        }        return properties;    }}

 

转载地址:http://krnzo.baihongyu.com/

你可能感兴趣的文章
表示数值的字符串
查看>>
JQUERY AJAX请求
查看>>
超级账本Fabric区块链用弹珠游戏Marbles 部署
查看>>
控制圈复杂度的9种重构技术总结
查看>>
数据分析--数字找朋友
查看>>
18年selenium3+python3+unittest自动化测试教程(下)
查看>>
memcache数据库和redis数据库的区别(理论)
查看>>
我的友情链接
查看>>
MyBatis+Spring结合
查看>>
Office 365之SkyDrive Pro
查看>>
无缝滚动实现原理分析【公告栏】
查看>>
Java Web 高性能开发
查看>>
CentOS 4.4双网卡绑定,实现负载均衡
查看>>
Scala之柯里化和隐式转换
查看>>
获取androdmanifest里面的meta-data
查看>>
mysql拷贝表的几种方式
查看>>
用设计模式去掉没必要的状态变量 —— 状态模式
查看>>
健忘的正则
查看>>
[转]CMake快速入门教程:实战
查看>>
IntelliJ IDEA创建JavaWeb工程及配置Tomcat部署
查看>>