Java中Properties类
1 简介:
JDK提供的java.util.Properties类继承自Hashtable类并且实现了Map接口,用map来存储key-value数据,所以存入的数据是无序的。其中键和值都是字符串类型。
2 java.util.Properties类
在Java中,其配置文件常为.properties文件,格式为文本文件,内容的格式为“键=值”的格式,#打头的是注释行,Properties会忽略注释。允许只有key没有value,没有value时,value会被set成null。java.util.Properties是对properties这类配置文件的映射。支持key-value类型和xml类型两种。java.util.Properties类提供了几个很重要的方法,归纳如下:
1) getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value值
2)setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
3)load( InputStream inStream),从输入流中读取属性列表(键值对)。通过对指定的文件进行装载来获取该文件中的所有键 - 值对以供 getProperty ( String key) 来搜索。load有两个方法的重载:load(InputStream inStream)、load(Reader reader),可根据不同的方式来加载属性文件。
InputStream inStream = TestProperties.class.getClassLoader().getResourceAsStream("demo.properties");
//通过当前类加载器的getResourceAsStream方法获取
//TestProperties当前类名;TestProperties.class.取得当前对象所属的Class对象; getClassLoader():取得该Class对象的类装载器
InputStream in = ClassLoader.getSystemResourceAsStream("filePath");
InputStream in = new BufferedInputStream(new FileInputStream(filepath));
InputStream inStream = new FileInputStream(new File("filePath")); //从文件获取
InputStream in = context.getResourceAsStream("filePath"); //在servlet中,可以通过context来获取InputStream
InputStream inStream = new URL("path").openStream(); //通过URL来获取
读取方法如下:
Properties pro = new Properties(); //实例化一个Properties对象
InputStream inStream = new FileInputStream("demo.properties"); //获取属性文件的文件输入流
pro.load(nStream);
inStream.close();
4)store( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
FileOutputStream outStream = new FileOutputStream("demo.properties");
pro.store(outStream,"Comment");
outStream.close();
5)clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
java.util.ResourceBundle类也提供了读取Properties配置文件的方法,ResourceBundle是一个抽象类。
附:ResourceBundle中的主要方法: 通过ResourceBundle.getBundle()静态方法来获取,此方法获取properties属性文件不需要加.properties后缀名。也可以从InputStream中获取ResourceBundle对象。在使用中遇到的问题可能是配置文件的路径,当配置文件不在当前类所在的包下,则需要使用包名限定;若属性文件在src根目录下,则直接使用demo.properties或demo即可。
ResourceBundle resource = ResourceBundle.getBundle("com/xiang/demo");//emo为属性文件名,放在包com.xiang下,如果是放在src下,直接用test即可
ResourceBundle resource1 = new PropertyResourceBundle(inStream);
String value = resource.getString("name");
3 Properties实例
1)Java虚拟机(JVM)有自己的配置文件(system.properties),如下就可以获得JVM的系统属性
import java.util.Properties;
public class ReadJVM {
public static void main(String[] args) {
Properties pps = System.getProperties();
pps.list(System.out);
}
}
2)新建一个配置文件Test.properties
name=JJ Weight=4444 Height=3333
public class getProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties pps = new Properties();
pps.load(new FileInputStream("Test.properties"));
//第一步就是要将文件读取到Properties类对象中,由于load有一个参数是InputStream,所以我们可以用 InputStream的子类FileInputStream将属性文件读取到Properties对象中,知道prop.properties的路径,我们就用FileInputStream(String name)构造函数:
Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
while(enum1.hasMoreElements()) {
String strKey = (String) enum1.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
}
}
}
如下类实现了Properties的常用操作
//关于Properties类常用的操作
public class TestProperties {
//根据Key读取Value
public static String GetValueByKey(String filePath, String key) {
Properties pps = new Properties();
try {
InputStream in = new BufferedInputStream (new FileInputStream(filePath));
pps.load(in);
String value = pps.getProperty(key);
System.out.println(key + " = " + value);
return value;
}catch (IOException e) {
e.printStackTrace();
return null;
}
}
//读取Properties的全部信息
public static void GetAllProperties(String filePath) throws IOException {
Properties pps = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
pps.load(in);
Enumeration en = pps.propertyNames(); //得到配置文件的名字
while(en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
}
}
//写入Properties信息
public static void WriteProperties (String filePath, String pKey, String pValue) throws IOException {
Properties pps = new Properties();
InputStream in = new FileInputStream(filePath);
//从输入流中读取属性列表(键和元素对)
pps.load(in);
//调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
//强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
OutputStream out = new FileOutputStream(filePath);
pps.setProperty(pKey, pValue);
//以适合使用 load 方法加载到 Properties 表中的格式,
//将此 Properties 表中的属性列表(键和元素对)写入输出流
pps.store(out, "Update " + pKey + " name");
}
public static void main(String [] args) throws IOException{
//String value = GetValueByKey("Test.properties", "name");
//System.out.println(value);
//GetAllProperties("Test.properties");
WriteProperties("Test.properties","long", "212");
}
}
结果:Test.properties中文件的数据为
#Update long name #Sun Feb 23 18:17:16 CST 2014 name=JJ Weight=4444 long=212 Height=3333
除此之外,java的properties文件需要放到classpath下面,这样程序才能读取到,有关classpath实际上就是java类或者库的存放路径,在java工程中,properties放到class文件一块。在web应用中,最简单的方法是放到web应用的WEB- INF\classes目录下即可,也可以放在其他文件夹下面,这时候需要在设置classpath环境变量的时候,将这个文件夹路径加到 classpath变量中,这样也也可以读取到。在此,你需要对classpath有个深刻理解,classpath绝非系统中刻意设定的那个系统环境变量,WEB-INF\classes其实也是,va工程的class文件目录也是。
在我们知道如何读写一个属性文件之后,我们仍然还有很多需要注意的问题,因为load和store方法都是按照ISO-8859-1的编码方式读写属性流文件的,而ILatin1 的字符和某些特殊字符,而对于非Latin1 的字符和某些特殊字符,则要使用与字符和字符串字面值所用的类似转义序列,以值和元素的形式来表示它们。所以当我们在处理中文时,不可以在直接修改属性文件时,将中文的值赋予给属性,而是要在JAVA程序中通过setProperty方法给属性赋予中文的值,因为这样store会将中文转换成 unicode码,在读取时系统会将读取到的unicode码按系统的编码打印出来,对于中文系统,通常是GBK码,这样中文才能够正常显示。
3)Java中Properties配置文件工具类
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
/**
* Java中Properties配置文件工具类
* @author shu
*
*/
public class PropsUtil {
private String path = "";
private Properties properties ;
/**
* 默认构造函数
*/
public PropsUtil() {}
/**
* 构造函数
* @param path 传入Properties地址值
*/
public PropsUtil(String path) {
this.path = path;
}
/**
* 加载properties文件
* @return 返回读取到的properties对象
*/
public Properties loadProps(){
InputStream inStream = ClassLoader.getSystemResourceAsStream(path);
try {
if(inStream==null)
throw new FileNotFoundException(path + " file is not found");
properties = new Properties();
properties.load(inStream);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}
/**
* 将配置写入到文件
*/
public void writeFile(){
// 获取文件输出流
try {
FileOutputStream outputStream = new FileOutputStream( new File(ClassLoader.getSystemResource(path).toURI()));
properties.store(outputStream, null);
outputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 通过关键字获取值
* @param key
* @return 返回对应的字符串,如果无,返回null
*/
public String getValueByKey(String key) {
if(properties==null)
properties = loadProps();
String val = properties.getProperty(key.trim());
return val;
}
/**
* 通过关键字获取值
* @param key 需要获取的关键字
* @param defaultValue 若找不到对应的关键字时返回的值
* @return 返回找到的字符串
*/
public String getValueByKey(String key,String defaultValue){
if(properties==null)
properties = loadProps();
return properties.getProperty(key, defaultValue);
}
/**
* 获取Properties所有的值
* @return 返回Properties的键值对
*/
public Map<String, String> getAllProperties() {
if(properties==null)
properties = loadProps();
Map<String, String> map = new HashMap<String, String>();
// 获取所有的键值
Iterator<String> it=properties.stringPropertyNames().iterator();
while(it.hasNext()){
String key=it.next();
map.put(key, properties.getProperty(key));
}
/*Enumeration enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
String value = getValueByKey(key);
map.put(key, value);
}*/
return map;
}
/**
* 往Properties写入新的键值且保存
* @param key 对应的键
* @param value 对应的值
*/
public void addProperties(String key, String value) {
if(properties==null)
properties = loadProps();
properties.setProperty(key, value);
try {
writeFile();
} catch (Exception e) {
throw new RuntimeException("write fail");
}
}
/**
* 更新配置文件
* @param key 对应的键
* @param value 对应的值
*/
public void update(String key,String value){
if(properties==null)
properties = loadProps();
if(properties.containsKey(key))
properties.replace(key, value);
try {
writeFile();
} catch (Exception e) {
throw new RuntimeException("write fail");
}
}
/**
* 刪除某一鍵值对
* @param key
*/
public void deleteByKey(String key){
if(properties==null)
properties = loadProps();
if(!properties.containsKey(key))
throw new RuntimeException("not such key");
properties.remove(key);
try {
writeFile();
} catch (Exception e) {
throw new RuntimeException("write fail");
}
}
/**
* 设置path值
* @param path
*/
public void setPath(String path){
this.path = path;
}
}
4 XML配置形式文件操作
xml形式的配置文件格式大略是这样:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>Hi</comment> <entry key="foo">bar</entry> <entry key="fu">baz</entry> </properties>
读取xml配置跟读取kv配置没差别,就是把load换成xml对应的loadFromXML方法,代码大略是这样:

1 public class LoadSampleXML {
2 public static void main(String args[]) throws Exception {
3 Properties prop = new Properties();
4 FileInputStream fis =
5 new FileInputStream("sampleprops.xml");
6 prop.loadFromXML(fis);
7 prop.list(System.out);
8 System.out.println("\nThe foo property: " +
9 prop.getProperty("foo"));
10 }
11 }

把内存中的properties对象写入到xml文件中也和上面差不多,就是把list方法改成xml对应的storeToXML方法。代码大略是这样:

1 import java.io.IOException;
2 import java.io.File;
3 import java.io.FileInputStream;
4 import java.io.PrintStream;
5 import java.util.Properties;
6
7 public class Test {
8 public static void main(String[] args) {
9 Properties p = new Properties();
10 p.setProperty("id","dean");
11 p.setProperty("password","123456");
12
13 try{
14 PrintStream fW = new PrintStream(new File("e:\\test1.xml"));
15 p.storeToXML(fW,"test");
16 } catch (IOException e) {
17 e.printStackTrace();
18 }
19 }
20 }
21

Java中Properties类的更多相关文章
- Java中Properties类的学习总结
学习目标: 1.认识properties文件,理解其含义,会正确创建properties文件. 2.会使用java.util.Properties类来操作properties文件. 一.认识prope ...
- Java中Properties类知识的总结
一.Properties类与配置文件 注意:是一个Map集合,该集合中的键值对都是字符串.该集合通常用于对键值对形式的配置文件进行操作. 配置文件:将软件中可变的部分数据可以定义到一个文件中,方便以后 ...
- Java中Properties类的操作
知识学而不用,就等于没用,到真正用到的时候还得重新再学.最近在看几款开源模拟器的源码,里面涉及到了很多关于Properties类的引用,由于Java已经好久没用了,而这些模拟器大多用Java来写,外加 ...
- Java中Properties类的操作配置文件
知识学而不用,就等于没用,到真正用到的时 候还得重新再学.最近在看几款开源模拟器的源码,里面涉及到了很多关于Properties类的引用,由于Java已经好久没用了,而这些模拟器大多用 Java来写, ...
- 对Java中properties类的理解
转载于:https://www.cnblogs.com/bakari/p/3562244.html 一.Java Properties类 Java中有个比较重要的类Properties(Java.ut ...
- java中Properties类及读取properties中属性值
本文为博主原创,未经允许不得转载: 在项目的应用中,经常将一些配置放入properties文件中,在代码应用中读取properties文件,就需要专门的类Properties类,通过这个类可以进行读取 ...
- Java 中 Properties 类的操作
一.Java Properties类 Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置 ...
- Java中Properties类的使用
1.properties介绍 java中的properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是"键=值&quo ...
- java编程中Properties类的具体作用和使用
如果不熟悉 java.util.Properties类,那么现在告诉您它是用来在一个文件中存储键-值对的,其中键和值是用等号分隔的.(如清单 1 所示).最近更新的java.util.Properti ...
随机推荐
- Ubuntu 16.04系统下安装RapidSVN版本控制器及配置diff,editor,merge和exploer工具
在Window下我们使用TortoiseSVN(小乌龟),可以很方便地进行查看.比较.更新.提交.回滚等SVN版本控制操作. 在Linux下我们可以使用RapidSVN.RapidSVN是一款轻量级的 ...
- 应不应该使用inline-block代替float
CSS布局创建网站,浮动绝对占据了很大的比例.大块区域如主内容及侧边栏,以及在其中的小块区域,都可以看到浮动的影子.这里浮动是唯一的解决方案吗? 浮动通常表现正常,但有时候搞起来会很纠结.特别是处理内 ...
- Linux下python开发环境的准备
升级python 安装依赖: yum install lrzsz zlib zlib-devel openssl readline-deve gcc ibffi-devel python-dev ...
- css3-逐帧动画
time,这里有两个时间,前面一个是规定完成这个动画所需要的时间,全称叫animation-duration,第二个time为动画延迟开始播放的时间,全称叫animation-delay,这两个数值可 ...
- 微服务架构的简单实现-Stardust
微服务架构,一个当下比较火的概念了.以前也只是了解过这方面的概念,没有尝试过.想找找.NET生态下面是否有现成的实现,可是没找到,就花了大半个月的闲暇时间,遵循着易用和简单,实现了一个微服务框架,我叫 ...
- js根据条件json生成随机json:randomjson
前端开发中,在做前后端分离的时候,经常需要手写json数据,有3个问题特别揪心: 1,数据是写死的,不能按一定的条件随机生成长度不一,内容不一的数据 2,写数组的时候,如果有很多条,需要一条一条地写, ...
- activiti 5.13 使用activiti设置用户组任务的 工作流的角色
1.设置activiti 流程引擎的用户,组别,关系/**在部署流程定义和启动流程实例的中间,设置组任务的办理人,向Activiti表中存放组和用户的信息*/ IdentityService iden ...
- 利用sub lr,lr,#4:程序是如何进行返回的?
1: ARM采用的是3级流水线 ARM的流水线结构为: 取指 -----> 译码 ------> 执行 ARM代码: PC PC- ...
- 代码编写规范说明书(c#.net与asp.net)
代码编写规范说明书(c#.net与asp.net) 目 录1 目的2 范围3 注释规范3.1 概述3.2 自建代码文件注释3.3 模块(类)注释3.4 类属性注释3.5 方法注释3.6 代码间注释4 ...
- 由if-else,switch代替方案引起的思考
关键词:条件判断,多态,策略模式,哈希表,字典map 笔者在用python实现事件驱动后,发现python是没有提供switch语句,python官方推荐多用字典来代替switch来实现,这让我就觉得 ...