当前位置: 移动技术网 > IT编程>开发语言>Java > 详解Java程序读取properties配置文件的方法

详解Java程序读取properties配置文件的方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

在我们平时写程序的时候,有些参数是经常改变的,而这种改变不是我们预知的。比如说我们开发了一个操作数据库的模块,在开发的时候我们连接本地的数据库那么ip ,数据库名称,表名称,数据库主机等信息是我们本地的,要使得这个操作数据的模块具有通用性,那么以上信息就不能写死在程序里。通常我们的做法是用配置文件来解决。
各种语言都有自己所支持的配置文件类型。比如python ,他支持.ini 文件。因为他内部有一个configparser 类来支持.ini 文件的读写,根据该类提供的方法程序员可以自由的来操作.ini 文件。而在java 中,java 支持的是.properties 文件的读写。jdk 内置的java.util.properties 类为我们操作.properties 文件提供了便利。

一..properties 文件的形式

# 以下为服务器、数据库信息
dbport = localhost 
databasename = mydb 
dbusername = root 
dbpassword = root 
# 以下为数据库表信息
dbtable = mytable 
# 以下为服务器信息
ip = 192.168.0.9 

上面的文件中我们假设该文件名为:test.properties 文件。其中# 开始的一行为注释信息;在等号“= ”左边的我们称之为key ;等号“= ”右边的我们称之为value 。(其实就是我们常说的键- 值对)key 应该是我们程序中的变量。而value 是我们根据实际情况配置的。

二.jdk 中的properties 类

properties 类存在于胞java.util 中,该类继承自hashtable,它提供了几个主要的方法:
1. getproperty(string key),  用指定的键在此属性列表中搜索属性。也就是通过参数key ,得到key 所对应的value 。
2. load(inputstream instream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的    test.properties 文件)进行装载来获取该文件中的所有键- 值对。以供getproperty(string key)来搜索。
3. setproperty(string key,string value),调用hashtable的方法put。他通过调用基类的put方法来设值键- 值对。
4. store(outputstream out,string comments),  以适合使用load方法加载到properties表中的格式,将此properties表中的属性列表(键和元素对)写入输出流。与load 方法相反,该方法将键- 值对写入到指定的文件中去。
5. clear(),清除所有装载的键 - 值对。该方法在基类中提供。
有了以上几个方法我们就可以对.properties 文件进行操作了!

三. java读取properties文件示例
有一个properties文件box.properties,内容如下:

color=red
name=box
length=18
width=7
heigth=8

获取其中的属性值,可用如下代码:

inputstream in = null;
properties p = new properties();
try {
  in = new bufferedinputstream(new fileinputstream("box.properties"));
  p.load(in);
} catch (filenotfoundexception e) {
  // todo auto-generated catch block
  e.printstacktrace();
} catch (ioexception e) {
  // todo auto-generated catch block
  e.printstacktrace();
}
enumeration<object> keys = p.keys();
while (keys.hasmoreelements()) {
  string key = (string) keys.nextelement();
  system.out.println(key + ":" + p.getproperty(key));
}

或者:

inputstream in;
resourcebundle rb = null;
try {
  in = new bufferedinputstream(new fileinputstream("box.properties"));
  rb = new propertyresourcebundle(in);
} catch (filenotfoundexception e1) {
  // todo auto-generated catch block
  e1.printstacktrace();
} catch (ioexception e) {
  // todo auto-generated catch block
  e.printstacktrace();
}
if (rb != null) {
  enumeration<string> keys = rb.getkeys();
  while (keys.hasmoreelements()) {
    string key = (string) keys.nextelement();
    system.out.println(key + ":" + rb.getstring(key));
  }
}

 不过输出顺序与原始文件不同。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网