欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-20 21:10:40
一、介绍 properties文件在java中主要为配置文件,文件类型为:.properties,格式为文本文件,内容格式为"键=值" 二、读取 这里我采用的是get...

一、介绍

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项目配置文件存放位置:

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

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

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

配置文件:

 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);
    
  }
}

运行结果:

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

封装的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配置文件详解整合,希望对大家有所帮助

上一篇:

下一篇: