欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-06-05 08:57:05|栏目:JAVA代码|点击:

一、介绍

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项目常用异常处理汇总

栏    目:JAVA代码

下一篇:Java Calendar日历类原理及使用方法

本文标题:Java读取.properties配置文件方法示例

本文地址:http://www.codeinn.net/misctech/135460.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有