`

加载和写入properties属性文件的工具类

阅读更多

很全面的工具类PropertiesTool,主要功能如下:

1,可以文件路径、字节流、字符流和编码等加载内容,

如loadFile(String filename,String encoding),loadStream(InputStream stream,String encoding)和loadReader(Reader reader)

2,在获取value时,可以主动将数据进行判断和类型转换,

如getStrings(String key,String regex),getCharacter(String key),getBoolean(String key)getInteger(String key)等

3,是否包含键和值,

如containsKey(String key)和containsValue(String value)

4,可以更改属性值,

如setValue(String key,String value)

5,可以获取key集合和键值对的Entry集合

如,getKeySet()和getEntrySet()

6,可以将已经加载和改变的所有东西,根据自定的字符编码,写入文件、字符流和字节流中,

如,writeToFile(String filename),writeToFile(String filename,String encoding),writeToStream(OutputStream stream,String encoding),writeToStream(OutputStream stream),writeToWriter(Writer writer)

 

工具类具体代码如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

/** 
 * @author: 			forestqqqq@163.com
 * @class:			PropertiesTool
 * @package:		test5
 * @description: 	加载属性文件中属性的工具类 ,应该是线程安全的
 */
public class PropertiesTool {
	private Properties tool;
	public PropertiesTool(){
		tool = new Properties();
	}
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			loadFile
	 * @description:	加载属性文件中的内容
	 * @param filename	属性文件路径
	 * @param encoding	文件的编码
	 * @return			是否加载成功,文件路径是否正确 
	 */
	public boolean loadFile(String filename,String encoding){
		try {
			FileInputStream in = new FileInputStream(filename);
			return loadStream(in,encoding);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			loadStream
	 * @description:	读取字节流加载内容
	 * @param stream	要读取的字节流
	 * @param encoding	字符流编码
	 * @return
	 */
	public boolean loadStream(InputStream stream,String encoding){
		try {
			Reader reader = new InputStreamReader(stream,encoding);
			return loadReader(reader);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			loadReader
	 * @description:	读取字符流加载内容
	 * @param reader	要读取的字符流
	 * @return
	 */
	public synchronized boolean loadReader(Reader reader){
		try {
			tool.load(reader);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getTool
	 * @description:	获取Properties类型加载器
	 * @return
	 */
	public synchronized Properties getTool(){
		return tool;
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getString
	 * @description:	加载一个字符串。如果没有对应的key,就返回null
	 * @param key		键值对中的key
	 * @return			键值对中的value
	 */
	public String getString(String key){
		return getTool().getProperty(key);
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getString
	 * @description:	加载一个字符串。如果没有对应的key,就返回默认值
	 * @param key		键值对中的key
	 * @param defaultValue	默认值
	 * @return			键值对中的value
	 */
	public String getString(String key,String defaultValue){
		return getTool().getProperty(key, defaultValue);
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getStrings
	 * @description:	加载一个String数组,并且以regex正则表达式分割该字符串。如果没有对应的key则返回null
	 * @param key		键值对中的key
	 * @param regex		正则表达式
	 * @return
	 */
	public String [] getStrings(String key,String regex){
		String str = getTool().getProperty(key);
		if(str == null){
			return null;
		}
		return str.split(regex);
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getCharacter
	 * @description:	加载一个Character。如果没有对应的key或者value的长度不是1,则返回null
	 * @param key
	 * @return
	 */
	public Character getCharacter(String key){
		String str = getTool().getProperty(key);
		if(str == null || str.length() != 1){
			return null;
		}
		return str.charAt(0);
	}
	
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getBoolean
	 * @description:	加载一个Boolean。如果没有对应的key,则返回null;如果值是"true"或"1",返回true,否则返回false
	 * @param key
	 * @return
	 */
	public Boolean getBoolean(String key){
		String str = getTool().getProperty(key);
		if(str == null){
			return null;
		}
		//这里比较"true"时,使用了不区分大小写的比较
		if("true".equalsIgnoreCase(str) || "1".equals(str)){
			return true;
		}
		return false;
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getInteger
	 * @description:	加载一个Integer。如果没有对应的key或者value无法转换成为Integer,则返回null
	 * @param key
	 * @return
	 */
	public Integer getInteger(String key){
		String str = getTool().getProperty(key);
		if(str == null){
			return null;
		}
		Integer value = null;
		try {
			value = Integer.parseInt(str);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return value;
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getLong
	 * @description:	加载一个Long。如果没有对应的key或者value无法转换成为Long,则返回null
	 * @param key
	 * @return
	 */
	public Long getLong(String key){
		String str = getTool().getProperty(key);
		if(str == null){
			return null;
		}
		Long value = null;
		try {
			value = Long.parseLong(str);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return value;
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getShort
	 * @description:	加载一个Short。如果没有对应的key或者value无法转换成为Short,则返回null
	 * @param key
	 * @return
	 */
	public Short getShort(String key){
		String str = getTool().getProperty(key);
		if(str == null){
			return null;
		}
		Short value = null;
		try {
			value = Short.parseShort(str);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return value;
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getByte
	 * @description:	加载一个Byte。如果没有对应的key或者value无法转换成为Byte,则返回null
	 * @param key
	 * @return
	 */
	public Byte getByte(String key){
		String str = getTool().getProperty(key);
		if(str == null){
			return null;
		}
		Byte value = null;
		try {
			value = Byte.parseByte(str);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return value;
	}
	
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getDouble
	 * @description:	加载一个Double。如果没有对应的key或者value无法转换成为Double,则返回null
	 * @param key
	 * @return
	 */
	public Double getDouble(String key){
		String str = getTool().getProperty(key);
		if(str == null){
			return null;
		}
		Double value = null;
		try {
			value = Double.parseDouble(str);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return value;
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getFloat
	 * @description:	加载一个Float。如果没有对应的key或者value无法转换成为Float,则返回null
	 * @param key
	 * @return
	 */
	public Float getFloat(String key){
		String str = getTool().getProperty(key);
		if(str == null){
			return null;
		}
		Float value = null;
		try {
			value = Float.parseFloat(str);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return value;
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			containsKey
	 * @description:	文件的键值对中是否包含该键
	 * @param key
	 * @return
	 */
	public boolean containsKey(String key){
		return getTool().containsKey(key);
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			containsValue
	 * @description:	文件的键值对中是否包含该值
	 * @param value
	 * @return
	 */
	public boolean containsValue(String value){
		return getTool().containsValue(value);
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getKeySet
	 * @description:	获取所有的键
	 * @return
	 */
	public Set<Object> getKeySet(){
		return getTool().keySet();
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			getEntrySet
	 * @description:	获取键值对的集合
	 * @return
	 */
	public Set<Entry<Object,Object>> getEntrySet(){
		return getTool().entrySet();
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			setValue
	 * @description:	为key设置值value
	 * @param key
	 * @param value
	 */
	public void setValue(String key,String value){
		getTool().setProperty(key, value);
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			writeToFile
	 * @description:	将已经加载的和改变的所有的东西写入文件中,如果该文件存在则覆盖,没有则创建,使用文件系统默认编码
	 * @param filename	要写入的文件的路径
	 * @return
	 */
	public boolean writeToFile(String filename){
		return writeToFile(filename,System.getProperty("file.encoding"));
	}
	
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			writeToFile
	 * @description:	将已经加载的和改变的所有的东西写入文件中,如果该文件存在则覆盖,没有则创建
	 * @param filename	要写入的文件的路径
	 * @param encoding	要写入的字符串的编码
	 * @return
	 */
	public boolean writeToFile(String filename,String encoding){
		//检查该文件是否存在,如果没有则创建
		File file = new File(filename);
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		//创建输出流
		try {
			FileOutputStream stream = new FileOutputStream(file);
			return writeToStream(stream,encoding);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			writeToStream
	 * @description:	将已经加载的和改变的所有的东西写入字节流中,使用文件指定的编码
	 * @param stream	要写入的字节流
	 * @param encoding	字符编码
	 * @return
	 */
	public boolean writeToStream(OutputStream stream,String encoding){
		try {
			OutputStreamWriter writer = new OutputStreamWriter(stream,encoding);
			return writeToWriter(writer);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			writeToStream
	 * @description:	将已经加载的和改变的所有的东西写入字节流中,使用文件系统默认编码
	 * @param stream	要写入的字节流
	 * @return
	 */
	public boolean writeToStream(OutputStream stream){
		return writeToStream(stream,System.getProperty("file.encoding"));
	}
	
	/** 
	 * @author: 			forestqqqq@163.com
	 * @method:			writeToWriter
	 * @description:	将已经加载的和改变的所有东西写入字符流中
	 * @param writer	要写入的字符流
	 * @return
	 */
	public boolean writeToWriter(Writer writer){
		try {
			getTool().store(writer, null);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}

 

下面是一个用于测试的属性文件内容,文件名叫test.properties,位于src/test5/目录下:

username=forest
password=forestqqqq
age=10
county=china
city=天津
man=true
hasChild=0
salary=100000000.0

 下面是一个用于测试的类

package test5;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class PropertiesTest {
	public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
		PropertiesTool pt = new PropertiesTool();
		String filename = new File("src/test5/test.properties").getAbsolutePath();
		System.out.println("filename==="+filename);
		System.out.println("加载结果==="+pt.loadFile(filename,"UTF-8"));
		System.out.println("**********下面输出一些键值对********");
		System.out.println("username=="+pt.getString("username"));
		System.out.println("city=="+pt.getString("city"));
		System.out.println("age=="+pt.getInteger("age"));
		System.out.println("man=="+pt.getBoolean("man"));
		System.out.println("hasChild=="+pt.getBoolean("hasChild"));
		System.out.println("salary=="+pt.getLong("salary"));
		System.out.println("salary=="+pt.getDouble("salary"));
		System.out.println("salary=="+pt.getFloat("salary"));
		System.out.println("**********下面输出所有的Key********");
		for(Object obj:pt.getKeySet()){
			System.out.println("key="+obj);
		}
		//pt.writeToFile("src/test5/test2.properties");
//		pt.writeToStream(
//				new FileOutputStream("src/test5/test2.properties"),"GBK");
		pt.setValue("username", "forestqqqq");
		pt.setValue("salary", "1000");
		pt.writeToWriter(
				new OutputStreamWriter(
						new FileOutputStream("src/test5/test2.properties"),"GBK"));
	}
}

 运行结果如下:

1),控制台输出:

filename===D:\JavaTest2\Test\src\test5\test.properties
加载结果===true
**********下面输出一些键值对********
username==forest
city==天津
age==10
man==true
hasChild==false
java.lang.NumberFormatException: For input string: "100000000.0"
	at java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.lang.Long.parseLong(Unknown Source)
	at java.lang.Long.parseLong(Unknown Source)
	at test5.PropertiesTool.getLong(PropertiesTool.java:202)
	at test5.PropertiesTest.main(PropertiesTest.java:21)
salary==null
salary==1.0E8
salary==1.0E8
**********下面输出所有的Key********
key=age
key=password
key=salary
key=hasChild
key=city
key=county
key=man
key=username

 输出的结果中有异常打印信息,因为salary的值无法转换成为Long类型数据

2)在src/test5/目录下生成文件test2.properties

 

1
2
分享到:
评论
2 楼 alvin198761 2013-07-08  
一句话的事情,非要搞一篇
1 楼 blackstreet 2013-07-07  
jdk自己就有 java.utilResourceBundle 直接搞定
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    Properties 文件比较工具

    `Properties`类允许加载和保存属性列表,支持键值对的形式,其中键和值都是字符串。通过调用`load()`方法可以从输入流中读取属性列表,而`store()`方法则可以将属性列表写入输出流。 `diffProperties.java`文件很...

    Property工具类,Properties文件工具类,PropertiesUtils工具类

    在Java编程中,`Property`工具类和`Properties`文件工具类是处理配置文件的关键组件。这些工具类帮助开发者读取、写入以及管理应用程序的配置信息,通常以`.properties`文件的形式存在。`.properties`文件是一种键值...

    读取Properties信息工具类

    在Java编程中,Properties类是用于处理属性文件的关键工具,它...通过创建这样的Properties工具类,我们可以简化与属性文件交互的代码,提高代码的可读性和可维护性。在实际项目中,这样的工具类是非常常见且实用的。

    读取properties返回map并写入文件

    读取.properties文件的主要工具有Java的Properties类。以下是一个简单的示例,展示如何使用Properties类加载文件并将其内容转换为Map: ```java import java.io.*; import java.util.*; public class ...

    一个获取属性文件的工具类

    `PropertiesUtil`类是一个实用工具类,设计用于简化读取、写入和操作这些属性文件的过程。在本文中,我们将深入探讨`PropertiesUtil`类的功能和实现细节。 首先,`PropertiesUtil`类可能包含以下几个核心方法: 1....

    能保存Properties文件注释的Properties工具类

    针对这个问题,开发者们创建了`CommentedProperties`这样的工具类,以保留属性文件中的注释信息。 `CommentedProperties`是基于Java的自定义Properties扩展,它的核心功能在于加载和保存文件时能够识别并保留注释。...

    java配置文件修改读取工具类,包括yml和properties类型文件

    总结来说,`YmlUtil.java`和`PropertiesUtil.java`是Java开发中的实用工具类,它们简化了YAML和Properties配置文件的读取和修改过程,提高了代码的可维护性和灵活性。理解和使用这些工具类,对于提升Java项目管理...

    XML和属性文件读取和写入

    XML(Extensible Markup Language)和属性文件(Properties File)是两种常见的数据存储格式,它们在软件开发中扮演着重要角色,特别是在配置管理、资源本地化和数据交换方面。本篇文章将详细探讨这两种文件的读取和...

    java 枚举遍历键值对 属性类Properties 类加载器

    而Properties类是Java中用于处理键值对的标准工具,它通常与类加载器协同工作来加载和存储配置信息。现在,我们将深入探讨这些概念。 首先,让我们来看看枚举。在Java中,枚举可以通过以下方式定义: ```java ...

    Java_Properties_类读取配置文件信息

    总结来说,`Properties` 类是 Java 中处理 `.properties` 配置文件的关键工具,它提供了方便的接口,让我们能够轻松地在程序中管理和操作配置信息。这使得 Java 应用程序能够适应不同环境,提升灵活性和可维护性。

    java操作properties属性文件jp.gr.java_conf.ussiy.app.propedit_5.3.3.jar,有例子

    Java操作Properties属性文件是Java开发中的常见任务,主要用于配置应用的参数或存储系统设置。`jp.gr.java_conf.ussiy.app.propedit_5.3.3.jar` 是一个专门用于编辑和管理Properties文件的工具,这使得开发者可以...

    基于属性文件的读取类

    `Properties`类提供了一系列方法来操作属性文件,比如`load()`和`store()`,分别用于加载和保存属性到文件中。以下是如何使用`Properties`类读取`db.properties`文件的基本步骤: 1. **加载属性文件**: 使用`...

    java获取properties属性文件示例

    总之,`Properties`类是Java中用于处理配置文件的关键工具,它提供了方便的方法来读取、修改和写入属性文件,使得应用程序的配置管理变得简单而有效。在实际项目中,合理使用`Properties`类能极大地提高代码的可维护...

    Properties类小结

    另外,Properties类还可以与其他工具类结合使用,例如ResourceBundle,以实现国际化(i18n)功能。通过不同语言的.properties文件,我们可以为不同地区的用户提供本地化的消息。 总结起来,Properties类是Java中...

    让spring加载自己的properties配置文件,在代码中获得配置信息

    在单元测试中,通常需要模拟配置环境,Spring JUnit提供了一些工具类和注解,如`@RunWith(SpringRunner.class)`和`@ContextConfiguration`,它们可以帮助我们在测试环境中加载特定的配置。 总的来说,Spring通过...

    属性文件读写操作类

    使用`Properties`类的`load()`方法可以从输入流中加载属性文件,如: ```java Properties props = new Properties(); FileInputStream fis = new FileInputStream("config.properties"); props.load(fis); fis...

    属性工具类(PropertyUtil)

    1. **读取属性文件**:工具类通常有一个静态方法如`loadProperties()`,用于加载指定路径或资源下的.properties文件。这个方法会返回一个`Properties`对象,其中包含了文件中的所有键值对。 2. **获取属性值**:...

    Properties文件读写;Property文件读写;Property

    3. **写入Properties文件**:为了更新或添加新的属性,`PropertyUtil.java`可能有一个`saveProperties(Properties props, String filePath)`方法,它接受一个`Properties`对象和文件路径,然后使用`Properties`的`...

    读取properties文件

    `Properties`类是Java中处理配置文件的强大工具,它不仅提供了加载和读取`.properties`文件的功能,还支持写入和保存属性,使得开发人员能够轻松地管理应用程序的各种配置信息。掌握`Properties`类的使用对于任何...

Global site tag (gtag.js) - Google Analytics