Properties文件工具类的使用--获取所有的键值、删除键、更新键等操作

  有时候我们希望处理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;
        try {
            String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();
            log.info("path -> {}", path);
            inputStream = new FileInputStream(new File(path));
            properties.load(inputStream);

            for (Entry<Object, Object> entry : properties.entrySet()) {
                log.info("key -> {}, value -> {}", entry.getKey(), entry.getValue());
            }

            // 保存到文件中(如果有的话会自动更新,没有会创建)
            inputStream.close();
        } catch (FileNotFoundException e) {
            log.error("saveOrUpdateProperty error", e);
        } catch (IOException e) {
            log.error("saveOrUpdateProperty error", e);
        }
        return "";
    }

    /**
     * 获取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。

public
class Properties extends Hashtable<Object,Object> {

     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保存到一个文件中。

原文地址:https://www.cnblogs.com/qlqwjy/p/9901797.html

时间: 2024-08-08 23:03:52

Properties文件工具类的使用--获取所有的键值、删除键、更新键等操作的相关文章

Java读取properties文件工具类并解决控制台中文乱码

1.建立properts文件(error.message.properties) HTTP201= 请求成功并且服务器创建了新的资源 2.在spring-mvc.xml文件(applicationContext-mvc.xml)中配置properties工具类路径及读取properties文件的路径 <bean id="propertyConfigurer" class="com.yjlc.platform.utils.PropertyConfigurer"

读取properties文件工具类

package com.paic.pad.info.common.utils; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; /** *@Title: *@Description:读取系统配置文件的工具类 */ public final class SystemResourceUtil { public static final String ENV_PROPERTY_KEY="a

读取Config文件工具类 PropertiesConfig.java

package com.util; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; /** * 读取Config文件工具类 * @version 1.0 * @since JDK 1.6 */ public class PropertiesConfig { /** * 获取整个配置文件中的属性 *

java中IO写文件工具类

下面是一些根据常用java类进行组装的对文件进行操作的类,平时,我更喜欢使用Jodd.io中提供的一些对文件的操作类,里面的方法写的简单易懂. 其中jodd中提供的JavaUtil类中提供的方法足够我们使用,里面的方法写的非常简练,例如append,read等方法,封装更好,更符合面向对象, 这里面我写的一些方法可多都是模仿jodd,从里面进行抽取出来的. /** * 获取路径文件夹下的所有文件 * @param path * @return */ public static File[] ge

自动扫描FTP文件工具类 ScanFtp.java

package com.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * 自动扫描FTP文件工具类 * 需要定时执行 */ public class S

java生成excel文件工具类实例

import java.io.File; import java.io.IOException; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; import org.

15 友盟项目--资源文件工具类(ResourceUtil)、sql执行工具类(ExecSQLUtil)

资源文件工具类把sql脚本转换为String字符串--->交给sql工具类ExecSQLUtil执行sql 1.资源文件工具类(ResourceUtil) 把sql脚本转换为String字符串 /** * 资源文件工具类 */ public class ResourceUtil { /** * 以String方式读取整个资源串 */ public static String readResourceAsString(String resource ,String charset) throws

获取资源文件工具类

如果没有依赖spring,可以将分割线下的方法去掉 import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.util.ResourceUtils

php简单实用的操作文件工具类(创建、移动、复制、删除)

php简单实用好用的文件及文件夹复制函数和工具类(创建.移动.复制.删除) function recurse_copy($src,$dst) {  // 原目录,复制到的目录 $dir = opendir($src); @mkdir($dst); while(false !== ( $file = readdir($dir)) ) { if (( $file != '.' ) && ( $file != '..' )) { if ( is_dir($src . '/' . $file) )