软件编程
位置:首页>> 软件编程>> java编程>> Java读取.properties配置文件方法示例

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

作者:黄浩#  发布时间:2023-08-24 16:32:56 

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

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

来源:https://www.cnblogs.com/hhmm99/p/9803119.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com