Java 操作Properties配置文件详解

 更新时间:2017年05月06日 14:34:23   作者:象  
本篇文章主要介绍了Java 操作Properties配置文件详解,详细的介绍了Properties和主要方法,有兴趣的可以了解下

1 简介:

JDK提供的java.util.Properties类继承自Hashtable类并且实现了Map接口,是使用一种键值对的形式来保存属性集,其中键和值都是字符串类型。

java.util.Properties类提供了getProperty()和setProperty()方法来操作属性文件,同时使用load()方法和store()方法加载和保存Properties配置文件。

java.util.ResourceBundle类也提供了读取Properties配置文件的方法,ResourceBundle是一个抽象类。

2.Properties中的主要方法

1)load(InputStream inStream):该方法可以从.properties属性文件对应的文件数入流中,加载属性列表到Properties类对象中。load有两个方法的重载:load(InputStream inStream)、load(Reader reader),可根据不同的方式来加载属性文件。

InputStream inStream = TestProperties.class.getClassLoader().getResourceAsStream("demo.properties"); 
//通过当前类加载器的getResourceAsStream方法获取
//TestProperties当前类名;TestProperties.class.取得当前对象所属的Class对象; getClassLoader():取得该Class对象的类装载器

InputStream in = ClassLoader.getSystemResourceAsStream("filePath");

InputStream inStream = new FileInputStream(new File("filePath")); //从文件获取
InputStream in = context.getResourceAsStream("filePath");     //在servlet中,可以通过context来获取InputStream
InputStream inStream = new URL("path").openStream();            //通过URL来获取

读取方法如下:

Properties pro = new Properties();                   //实例化一个Properties对象
InputStream inStream = new FileInputStream("demo.properties");     //获取属性文件的文件输入流
pro.load(nStream);
inStream.close();

 2)store(OutputStream out,String comments):这个方法将Properties类对象的属性列表写入.properties配置文件。如下:

FileOutputStream outStream = new FileOutputStream("demo.properties");
pro.store(outStream,"Comment");
outStream.close();

3 ResourceBundle中的主要方法

 通过ResourceBundle.getBundle()静态方法来获取,此方法获取properties属性文件不需要加.properties后缀名。也可以从InputStream中获取ResourceBundle对象。

ResourceBundle resource = ResourceBundle.getBundle("com/xiang/demo");//emo为属性文件名,放在包com.xiang下,如果是放在src下,直接用test即可 
ResourceBundle resource1 = new PropertyResourceBundle(inStream);  
String value = resource.getString("name"); 

在使用中遇到的问题可能是配置文件的路径,当配置文件不在当前类所在的包下,则需要使用包名限定;若属性文件在src根目录下,则直接使用demo.properties或demo即可。

4 Properties操作实例

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * Java中Preperties配置文件工具类
 * @author shu
 *
 */
public class PropsUtil {
  private String path = "";
  private Properties properties ;
  
  /**
   * 默认构造函数
   */
  public PropsUtil() {}
  
  /**
   * 构造函数
   * @param path 传入Properties地址值
   */
  public PropsUtil(String path) {
    this.path = path;
  }
  
  /**
   * 加载properties文件
   * @return 返回读取到的properties对象
   */
  public Properties loadProps(){
    InputStream inStream = ClassLoader.getSystemResourceAsStream(path);    
    try {
      if(inStream==null)
        throw new FileNotFoundException(path + " file is not found");
      properties = new Properties();
      properties.load(inStream);
      inStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return properties;
  }
  
  /**
   * 将配置写入到文件
   */
  public void writeFile(){
    // 获取文件输出流
    try {
      FileOutputStream outputStream = new FileOutputStream( new File(ClassLoader.getSystemResource(path).toURI()));
      properties.store(outputStream, null);
      outputStream.close();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
  /**
   * 通过关键字获取值
   * @param key
   * @return 返回对应的字符串,如果无,返回null
   */
  public String getValueByKey(String key) {
    if(properties==null)
      properties = loadProps();
    String val = properties.getProperty(key.trim());
    return val;
  }
  
  /**
   * 通过关键字获取值
   * @param key 需要获取的关键字
   * @param defaultValue 若找不到对应的关键字时返回的值
   * @return 返回找到的字符串
   */
  public String getValueByKey(String key,String defaultValue){
    if(properties==null)
      properties = loadProps();
    return properties.getProperty(key, defaultValue);
  }
  
  /**
   * 获取Properties所有的值
   * @return 返回Properties的键值对
   */
  public Map<String, String> getAllProperties() {
    if(properties==null)
      properties = loadProps();
    Map<String, String> map = new HashMap<String, String>();
    // 获取所有的键值
    Iterator<String> it=properties.stringPropertyNames().iterator();
    while(it.hasNext()){
      String key=it.next();
      map.put(key, properties.getProperty(key));
    }
    /*Enumeration enumeration = properties.propertyNames();
    while (enumeration.hasMoreElements()) {
      String key = (String) enumeration.nextElement();
      String value = getValueByKey(key);
      map.put(key, value);
    }*/
    return map;
  }

  /**
   * 往Properties写入新的键值且保存
   * @param key 对应的键
   * @param value 对应的值
   */
  public void addProperties(String key, String value) {
    if(properties==null)
      properties = loadProps();
    properties.setProperty(key, value);
    try {
      writeFile();
    } catch (Exception e) {
      throw new RuntimeException("write fail");
    }
  }
  
  /**
   * 更新配置文件
   * @param key 对应的键
   * @param value 对应的值
   */
   public void update(String key,String value){
     if(properties==null)
      properties = loadProps();
     if(properties.containsKey(key))
       properties.replace(key, value);
    try {
      writeFile();
    } catch (Exception e) {
      throw new RuntimeException("write fail");
    }
   }
   
   /**
   * 刪除某一鍵值对
   * @param key
   */
   public void deleteByKey(String key){
     if(properties==null)
      properties = loadProps();
     if(!properties.containsKey(key))
       throw new RuntimeException("not such key");
     properties.remove(key);
     try {
      writeFile();
     } catch (Exception e) {
      throw new RuntimeException("write fail");
    }
   }
   
   /**
   * 设置path值
   * @param path
   */
   public void setPath(String path){
     this.path = path;
   }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 基于eclipse-temurin镜像部署spring boot应用的实现示例

    基于eclipse-temurin镜像部署spring boot应用的实现示例

    本文提供了基于eclipse-temurin镜像部署Spring Boot应用的详细实现示例,通过使用Docker镜像,可以轻松地创建和管理Spring Boot应用程序的容器化环境,感兴趣的可以了解一下
    2023-08-08
  • 接口重试的7种常用方案详细介绍

    接口重试的7种常用方案详细介绍

    这篇文章主要为大家详细介绍了接口重试的7种常用方案,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以根据需求选择
    2025-03-03
  • 利用Jackson实现数据脱敏的示例详解

    利用Jackson实现数据脱敏的示例详解

    在我们的企业项目中,为了保护用户隐私,数据脱敏成了必不可少的操作,那么我们怎么优雅的利用Jackson实现数据脱敏呢,本文就来和大家详细聊聊,希望对大家有所帮助
    2023-05-05
  • Java列表元素自定义排序方式

    Java列表元素自定义排序方式

    文章介绍了在Java开发中如何对列表元素进行自定义排序,通过实现`Comparator`接口并重写`compare`方法来指定自定义排序规则,示例展示了如何对汉字数字进行排序,并通过改变自定义顺序列表的元素添加顺序来实现倒序排序
    2024-12-12
  • Spring IOC (DI) 依赖注入的四种方式示例详解

    Spring IOC (DI) 依赖注入的四种方式示例详解

    这篇文章主要介绍了Spring IOC (DI) 依赖注入的四种方式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-06-06
  • java判断字符串是否为数字的方法小结

    java判断字符串是否为数字的方法小结

    这篇文章主要介绍了java判断字符串是否为数字的方法,分别讲述了使用Java自带函数、正则表达式及ascii码三种方法进行字符串判断的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-11-11
  • Java中实现String.padLeft和String.padRight的示例

    Java中实现String.padLeft和String.padRight的示例

    本篇文章主要介绍了Java中实现String.padLeft和String.padRight,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • Java为何需要平衡方法调用与内联

    Java为何需要平衡方法调用与内联

    这篇文章主要介绍了Java为何需要平衡方法调用与内联,帮助大家更好的理解和使用Java,感兴趣的朋友可以了解下
    2021-01-01
  • SpringBoot最简洁的国际化配置

    SpringBoot最简洁的国际化配置

    这篇文章主要介绍了SpringBoot最简洁的国际化配置,Spring Boot是一个用于构建独立的、生产级别的Spring应用程序的框架,国际化是一个重要的功能,它允许应用程序根据用户的语言和地区显示不同的内容,在Spring Boot中,实现国际化非常简单,需要的朋友可以参考下
    2023-10-10
  • Spring创建bean实例的几种方式分享

    Spring创建bean实例的几种方式分享

    这篇文章主要介绍了Spring创建bean实例的几种方式分享,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-07-07

最新评论