Java读取.properties配置文件方法示例

时间:2019-03-15
这篇文章主要介绍了Java读取.properties配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、介绍

Properties文件在Java中主要为配置文件,文件类型为:.properties,格式为文本文件,内容格式为"键=值"

二、读取

这里我采用的是getResourceAsStream的文件读取方法

如果想要使用这个方法,则需要了解一些基本使用信息:

1、读取文件路径范围:只局限于工程的源文件中

2、文件访问形式:带"/"是绝对路径,不带"/"是相对路径

3、读取文件类型:主要为:.properties文件,.xml文件

三、使用

主要方法有:

  1. 1、 load ( InputStream  inStream) :从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如的 beans.properties 文件)进行装载来获取该文件中的所有键 - 值对。
  2. 2、 setProperty ( String  key, String  value) :调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
  3. 3、 getProperty ( String  key) :用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
  4. 4、 store ( OutputStream  out, String  comments) :以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
  5. 5、 clear ():清除所有装载的 键 - 值对。该方法在基类中提供。

java项目配置文件存放位置:

 Maven项目配置文件存放位置:

配置文件:

 className = edu.nf.ch02.impl.Sub

 java代码:

public class Main {

  public static void main(String[] args) throws IOException {
    //创建Properties对象
    Properties prop = new Properties();
    //读取classPath中的properties文件
    prop.load(Main.class.getClassLoader().getResourceAsStream("bean.properties"));
    //根据键取出值
    String className = prop.getProperty("className");
    System.out.println(className);
    
  }
}

运行结果:

封装的PropertiesUtil工具类:

public class PropertyUtil {

  private static Properties prop = new Properties();

  static {
    try {
      prop.load(PropertyUtil.class.getClassLoader().getResourceAsStream("calculator.properties"));
    } catch (IOException e) {
      throw new RuntimeException(e.getMessage());
    }
  }

  /**
   * 根据Name获取Property
   * @param name
   * @return
   */
  public static String getProperty(String name) {
    return prop.getProperty(name);
  }

  /**
   * 获取所有的Property
   * @return
   */
  public static List<String> getBeanFactoryClass() {
    List<String> list = new ArrayList<>();
    Set<String> keys = prop.stringPropertyNames();
    for (String key : keys) {
      list.add(prop.getProperty(key));
    }
    return list;
  }
}

以上所述是小编给大家介绍的Java读取.properties配置文件详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!