Properties类使用详解
Java Properties类使用详解
概述
Properties 继承于 Hashtable。表示一个持久的属性集,属性列表以key-value的形式存在,key和value都是字符串。
Properties 类被许多Java类使用。例如,在获取环境变量时它就作为System.getProperties()方法的返回值。
我们在很多需要避免硬编码的应用场景下需要使用properties文件来加载程序需要的配置信息,比如JDBC、MyBatis框架等。Properties类则是properties文件和程序的中间桥梁,不论是从properties文件读取信息还是写入信息到properties文件都要经由Properties类。
常见方法
除了从Hashtable中所定义的方法,Properties定义了以下方法:

下面我们从写入、读取、遍历等角度来解析Properties类的常见用法:
写入
Properties类调用setProperty方法将键值对保存到内存中,此时可以通过getProperty方法读取,propertyNames方法进行遍历,但是并没有将键值对持久化到属性文件中,故需要调用store方法持久化键值对到属性文件中。
package cn.habitdiary;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties; import junit.framework.TestCase; public class PropertiesTester extends TestCase { public void writeProperties() {
Properties properties = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("config.properties");
properties.setProperty("url", "jdbc:mysql://localhost:3306/");
properties.setProperty("username", "root");
properties.setProperty("password", "root");
properties.setProperty("database", "users");//保存键值对到内存
properties.store(output, "Steven1997 modify" + new Date().toString());
// 保存键值对到文件中
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
读取
下面给出常见的六种读取properties文件的方式:
package cn.habitdiary; import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle; /**
* 读取properties文件的方式
*
*/
public class LoadPropertiesFileUtil { private static String basePath = "src/main/java/cn/habitdiary/prop.properties";
private static String path = ""; /**
* 一、 使用java.util.Properties类的load(InputStream in)方法加载properties文件
*
* @return
*/
public static String getPath1() { try {
InputStream in = new BufferedInputStream(new FileInputStream(
new File(basePath)));
Properties prop = new Properties(); prop.load(in); path = prop.getProperty("path"); } catch (FileNotFoundException e) {
System.out.println("properties文件路径书写有误,请检查!");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} return path;
} /**
* 二、 使用java.util.ResourceBundle类的getBundle()方法
* 注意:这个getBundle()方法的参数只能写成包路径+properties文件名,否则将抛异常
*
* @return
*/
public static String getPath2() {
ResourceBundle rb = ResourceBundle
.getBundle("cn/habitdiary/prop");
path = rb.getString("path");
return path;
} /**
* 三、 使用java.util.PropertyResourceBundle类的构造函数
*
* @return
*/
public static String getPath3() {
InputStream in;
try {
in = new BufferedInputStream(new FileInputStream(basePath));
ResourceBundle rb = new PropertyResourceBundle(in);
path = rb.getString("path");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return path;
} /**
* 四、 使用class变量的getResourceAsStream()方法
* 注意:getResourceAsStream()方法的参数按格式写到包路径+properties文件名+.后缀
*
* @return
*/
public static String getPath4() {
InputStream in = LoadPropertiesFileUtil.class
.getResourceAsStream("cn/habitdiary/prop.properties");
Properties p = new Properties();
try {
p.load(in);
path = p.getProperty("path");
} catch (IOException e) {
e.printStackTrace();
}
return path;
} /**
* 五、
* 使用class.getClassLoader()所得到的java.lang.ClassLoader的
* getResourceAsStream()方法
* getResourceAsStream(name)方法的参数必须是包路径+文件名+.后缀
* 否则会报空指针异常
* @return
*/
public static String getPath5() {
InputStream in = LoadPropertiesFileUtil.class.getClassLoader()
.getResourceAsStream("cn/habitdiary/prop.properties");
Properties p = new Properties();
try {
p.load(in);
path = p.getProperty("path");
} catch (IOException e) {
e.printStackTrace();
}
return path;
} /**
* 六、 使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
* getSystemResourceAsStream()方法的参数格式也是有固定要求的
*
* @return
*/
public static String getPath6() {
InputStream in = ClassLoader
.getSystemResourceAsStream("cn/habitdiary/prop.properties");
Properties p = new Properties();
try {
p.load(in);
path = p.getProperty("path");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return path;
} public static void main(String[] args) {
System.out.println(LoadPropertiesFileUtil.getPath1());
System.out.println(LoadPropertiesFileUtil.getPath2());
System.out.println(LoadPropertiesFileUtil.getPath3());
System.out.println(LoadPropertiesFileUtil.getPath4());
System.out.println(LoadPropertiesFileUtil.getPath5());
System.out.println(LoadPropertiesFileUtil.getPath6());
}
}
其中第一、四、五、六种方式都是先获得文件的输入流,然后通过Properties类的load(InputStream inStream)方法加载到Properties对象中,最后通过Properties对象来操作文件内容。
第二、三中方式是通过ResourceBundle类来加载Properties文件,然后ResourceBundle对象来操做properties文件内容。
其中最重要的就是每种方式加载文件时,文件的路径需要按照方法的定义的格式来加载,否则会抛出各种异常,比如空指针异常。
遍历
下面给出四种遍历Properties中的所有键值对的方法:
/**
* 输出properties的key和value
*/
public static void printProp(Properties properties) {
System.out.println("---------(方式一)------------");
for (String key : properties.stringPropertyNames()) {
System.out.println(key + "=" + properties.getProperty(key));
} System.out.println("---------(方式二)------------");
Set<Object> keys = properties.keySet();//返回属性key的集合
for (Object key : keys) {
System.out.println(key.toString() + "=" + properties.get(key));
} System.out.println("---------(方式三)------------");
Set<Map.Entry<Object, Object>> entrySet = properties.entrySet();
//返回的属性键值对实体
for (Map.Entry<Object, Object> entry : entrySet) {
System.out.println(entry.getKey() + "=" + entry.getValue());
} System.out.println("---------(方式四)------------");
Enumeration<?> e = properties.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = properties.getProperty(key);
System.out.println(key + "=" + value);
}
}
Properties类使用详解的更多相关文章
- log4j.properties 的使用详解
一.log4j.properties 的使用详解 1.输出级别的种类 ERROR.WARN.INFO.DEBUGERROR 为严重错误 主要是程序的错误WARN 为一般警告,比如session丢失IN ...
- qml学习笔记(二):可视化元素基类Item详解(上半场anchors等等)
原博主博客地址:http://blog.csdn.net/qq21497936本文章博客地址:http://blog.csdn.net/qq21497936/article/details/78516 ...
- UML类图详解_关联关系_一对多
对于一对多的示例,可以想象一个账户可以多次申购.在申购的时候没有固定上限,下限为0,那么就可以使用容器类(container class)来搞,最常见的就是vector了. 下面我们来看一个“一对多” ...
- UML类图详解_关联关系_多对一
首先先来明确一个概念,即多重性.什么是多重性呢?多重性是指两个对象之间的链接数目,表示法是“下限...上限”,最小数据为零(0),最大数目为没有设限(*),如果仅标示一个数目级上下限相同. 实际在UM ...
- Android中Application类的详解:
Android中Application类的详解: 我们在平时的开发中,有时候可能会须要一些全局数据.来让应用中的全部Activity和View都能訪问到.大家在遇到这样的情况时,可能首先会想到自定义一 ...
- Delphi中的线程类 - TThread详解
Delphi中的线程类 - TThread详解 2011年06月27日 星期一 20:28 Delphi中有一个线程类TThread是用来实现多线程编程的,这个绝大多数Delphi书藉都有说到,但基本 ...
- UML简单介绍—类图详解
类图详解 阅读本文前请先阅读:UML简单介绍—类图这么看就懂了 1.泛化关系 一个动物类: /** * 动物类 */ public class Animal { public String name; ...
- 在java poi导入Excel通用工具类示例详解
转: 在java poi导入Excel通用工具类示例详解 更新时间:2017年09月10日 14:21:36 作者:daochuwenziyao 我要评论 这篇文章主要给大家介绍了关于在j ...
- spring boot 配置文件properties和YAML详解
spring boot 配置文件properties和YAML详解 properties中配置信息并获取值. 1:在application.properties配置文件中添加: 根据提示创建直接创建. ...
随机推荐
- [golang][译]使用os/exec执行命令
[golang][译]使用os/exec执行命令 https://colobu.com/2017/06/19/advanced-command-execution-in-Go-with-os-exec ...
- 服务器上build.xml文件乱码解决(亲测有效)
前提条件:必须root账户登录系统,否则无权限 1. 修改/etc/sysconfig/i18n: 拷贝如下内容到文件中 #LANG="zh_CN.UTF-8" LANG=&quo ...
- hbase 在线修复集群命令
前提:HDFS fsck确保hbase根目录下文件没有损坏丢失,如果有,则先进行corrupt block移除. 切记:一定要在所有Region都上线之后再修复,否则修复之后可能出现重复Region. ...
- 实验五 遇到的问题:openssl: error while loading shared libraries: libssl.so.1.1
遇到的问题 命令行:linux@ubuntu64-vm:~/exp/exp5$ openssl enc -aes-128-cbc -in test_aes.txt -out out.txt -pass ...
- windows下CEF3的关闭流程《转》
原文地址:https://github.com/fanfeilong/cefutil/blob/master/doc/CEF_Close.md ============================ ...
- 信息论 | information theory | 信息度量 | information measures | R代码(一)
这个时代已经是多学科相互渗透的时代,纯粹的传统学科在没落,新兴的交叉学科在不断兴起. life science neurosciences statistics computer science in ...
- springboot前端传参date类型后台处理方式
转载:https://blog.csdn.net/xiangluer/article/details/81913137?utm_source=copy 参考如下博客: https://www.jian ...
- MQTT 客户端应用及常见问题(C#)
https://blog.csdn.net/dengyaan/article/details/51752327 最近因为工作需要,需要使用C# 语言编写一个通过MQTT协议 ,上传数据到云端的工具.因 ...
- gitlab 默认端口修改文件
vim /var/opt/gitlab/nginx/conf/gitlab-http.conf listen *:80;
- Hive的配置详解和日常维护
Hive的配置详解和日常维护 一.Hive的参数配置详解 1>.mapred.reduce.tasks 默认为-1.指定Hive作业的reduce task个数,如果保留默认值,则Hive 自 ...