java读写Properties属性文件公用方法

合集下载

java读写Properties属性文件公用方法

java读写Properties属性文件公用方法

java读写Properties属性文件公用方法在Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。

在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。

Properties提供了如下几个主要的方法: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 (),清除所有装载的键- 值对。

该方法在基类中提供。

以下提供一套读写配置文件的公用实用方法,我们以后可以在项目中进行引入。

import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import java.util.Properties;import org.apache.log4j.Logger;public class PropertieUtil {//设置日志private static Logger logger=Logger.getLogger(PropertieUtil.class);private PropertieUtil() {}/*** 读取配置文件某属性*/public static String readValue(String filePath,String key) {Properties props=new Properties();try {if(filePath.startsWith("/")) {filePath="/"+filePath;}InputStream in=PropertieUtil.class.getResourceAsStream(filePath);props.load(in);String value=props.getProperty(key);return value;} catch (IOException e) {// TODO Auto-generated catch blocklogger.error(e);return null;}}/*** 打印配置文件全部内容*/public static void readProperties(String filePath) {Properties props=new Properties();try {if(!filePath.startsWith("/")) {filePath="/"+filePath;}InputStream in=PropertieUtil.class.getResourceAsStream(filePath);props.load(in);Enumeration<?> en=props.propertyNames();//遍历打印while(en.hasMoreElements()) {String key=(String)en.nextElement();String property=props.getProperty(key);//日志信息显示键和值(key+":"+property);}}catch(Exception e) {//日志显示错误信息logger.error(e);}}最后测试效果如下:调用:readProperties("jdbc.properties");调用writeProperties("test.properties","test","test");。

JAVAProperties配置文件的读写

JAVAProperties配置文件的读写

JAVAProperties配置⽂件的读写 通常我们就会看到⼀个配置⽂件,⽐如:jdbc.properties,它是以“.properties”格式结尾的。

在java中,这种⽂件的内容以键值对<key,value>存储,通常以“=”分隔key和value,当然也可以⽤":"来分隔,但通常不这么⼲。

读取配置⽂件 这⾥有⼀个⽂件叫asfds.properties,⾥⾯简单的存了两个键值对,如下图所⽰: 读取配置⽂件的基本步骤是:1. 实例化⼀个Properties对象;2. 将要读取的⽂件放⼊数据流中;3. 调⽤Properties对象的load⽅法,将属性⽂件的键值对加载到Properties类对象中;4. 调⽤Properties对象的getProperty(String key)读⼊对应key的value值。

注:如果想要读取key值,可以调⽤Properties对象的stringPropertyNames()⽅法获取⼀个set集合,然后遍历set集合即可。

读取配置⽂件的⽅法: 1/**2 * read properties file3 * @param paramFile file path4 * @throws Exception5*/6public static void inputFile(String paramFile) throws Exception7 {8 Properties props=new Properties();//使⽤Properties类来加载属性⽂件9 FileInputStream iFile = new FileInputStream(paramFile);10 props.load(iFile);1112/**begin*******直接遍历⽂件key值获取*******begin*/13 Iterator<String> iterator = props.stringPropertyNames().iterator();14while (iterator.hasNext()){15 String key = iterator.next();16 System.out.println(key+":"+props.getProperty(key));17 }18/**end*******直接遍历⽂件key值获取*******end*/1920/**begin*******在知道Key值的情况下,直接getProperty即可获取*******begin*/21 String user=props.getProperty("user");22 String pass=props.getProperty("pass");23 System.out.println("\n"+user+"\n"+pass);24/**end*******在知道Key值的情况下,直接getProperty即可获取*******end*/25 iFile.close();2627 }写⼊配置⽂件 写⼊配置⽂件的基本步骤是:1. 实例化⼀个Properties对象;2. 获取⼀个⽂件输出流对象(FileOutputStream);3. 调⽤Properties对象的setProperty(String key,String value)⽅法设置要存⼊的键值对放⼊⽂件输出流中;4. 调⽤Properties对象的store(OutputStream out,String comments)⽅法保存,comments参数是注释; 写⼊配置⽂件的⽅法:1/**2 *write properties file3 * @param paramFile file path4 * @throws IOException5*/6private static void outputFile(String paramFile) throws IOException {7///保存属性到b.properties⽂件8 Properties props=new Properties();9 FileOutputStream oFile = new FileOutputStream(paramFile, true);//true表⽰追加打开10 props.setProperty("testKey", "value");11//store(OutputStream,comments):store(输出流,注释) 注释可以通过“\n”来换⾏12 props.store(oFile, "The New properties file Annotations"+"\n"+"Test For Save!");13 oFile.close();14 }测试输出 ⽂件读取: @Testpublic void testInputFile(){//read properties filetry {inputFile("resources/asfds.properties");} catch (Exception e) {e.printStackTrace();}} 输出: ⽂件写⼊:@Testpublic void testOutputFile(){//write properties filetry {outputFile("resources/test.properties");} catch (Exception e) {e.printStackTrace();}} 写⼊的⽂件:。

Properties类操作.properties配置文件方法总结

Properties类操作.properties配置文件方法总结

Properties类操作.properties配置⽂件⽅法总结⼀、properties⽂件Properties⽂件是java中很常⽤的⼀种配置⽂件,⽂件后缀为“.properties”,属⽂本⽂件,⽂件的内容格式是“键=值”的格式,可以⽤“#”作为注释,java编程中⽤到的地⽅很多,运⽤配置⽂件,可以便于java深层次的解耦。

例如java应⽤通过JDBC连接数据库时,可以把数据库的配置写在配置⽂件 jdbc.properties:driver=com.mysql.jdbc.DriverjdbcUrl=jdbc:mysql://localhost:3306/useruser=rootpassword=123456这样我们就可以通过加载properties配置⽂件来连接数据库,达到深层次的解耦⽬的,如果想要换成oracle或是DB2,我们只需要修改配置⽂件即可,不⽤修改任何代码就可以更换数据库。

⼆、Properties类java中提供了配置⽂件的操作类Properties类(java.util.Properties):读取properties⽂件的通⽤⽅法:根据键得到value/*** 读取config.properties⽂件中的内容,放到Properties类中* @param filePath ⽂件路径* @param key 配置⽂件中的key* @return返回key对应的value*/public static String readConfigFiles(String filePath,String key) {Properties prop = new Properties();try{InputStream inputStream = new FileInputStream(filePath);prop.load(inputStream);inputStream.close();return prop.getProperty(key);}catch (Exception e) {e.printStackTrace();System.out.println("未找到相关配置⽂件");return null;}}把配置⽂件以键值对的形式存放到Map中:/*** 把.properties⽂件中的键值对存放在Map中* @param inputStream 配置⽂件(inputstream形式传⼊)* @return返回Map*/public Map<String, String> convertPropertityFileToMap(InputStream inputStream) {try {Properties prop = new Properties();Map<String, String> map = new HashMap<String, String>();if (inputStream != null) {prop.load(inputStream);Enumeration keyNames = prop.propertyNames();while (keyNames.hasMoreElements()) {String key = (String) keyNames.nextElement();String value = prop.getProperty(key);map.put(key, value);}return map;} else {return null;}} catch (Exception e) {e.printStackTrace();return null;}}。

Java程序读取配置文件的几种方法

Java程序读取配置文件的几种方法

Java程序读取配置⽂件的⼏种⽅法Java 开发中,需要将⼀些易变的配置参数放置再 XML 配置⽂件或者 properties 配置⽂件中。

然⽽ XML 配置⽂件需要通过 DOM 或 SAX ⽅式解析,⽽读取 properties 配置⽂件就⽐较容易。

1. 读取properties⽂件的⽅法1. 使⽤类加载器ClassLoder类读取配置⽂件InputStream in = MainClass.class.getClassLoader().getResourceAsStream("com/demo/config.properties");MainClass.class是主类的反射对象,因为getClassLoader()是class类的对象⽅法。

在类加载器中调⽤getResourceAsStream()时,采⽤相对路径,起始位置在src⽬录,路径开头没有“/”。

InputStream in = (new MainClass()).getClass().getClassLoader().getResourceAsStream("com/demo/config.properties");因为getClass()是object类的对象⽅法,所有在主类调⽤时要将主类实体化,即new MainClass()。

同理,相对路径起始位置同上。

2. ⽤class对象读取配置⽂件之所以Class对象也可以加载资源⽂件是因为Class类封装的getResourceAsStream⽅法的源码中调⽤了类加载器。

InputStream in = MainClass.class.getResourceAsStream(“/com/demo/config.properties”);同样MainClass.class是主类的反射对象。

在class对象中调⽤getResourceAsStream()时,采⽤绝对路径,起始位置在类路径(bin⽬录),因此路径要以“/”开头。

五种方式让你在java中读取properties文件内容不再是难题

五种方式让你在java中读取properties文件内容不再是难题

五种⽅式让你在java中读取properties⽂件内容不再是难题 最近,在项⽬开发的过程中,遇到需要在properties⽂件中定义⼀些⾃定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题。

就借此机会把Spring+SpringMVC+Mybatis整合开发的项⽬中通过java程序读取properties⽂件内容的⽅式进⾏了梳理和分析,现和⼤家共享。

Spring 4.2.6.RELEASESpringMvc 4.2.6.RELEASEMybatis 3.2.8Maven 3.3.9Jdk 1.7Idea 15.04⽅式1.通过context:property-placeholder加载配置⽂件jdbc.properties中的内容<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/> 上⾯的配置和下⾯配置等价,是对下⾯配置的简化<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="ignoreUnresolvablePlaceholders" value="true"/><property name="locations"><list><value>classpath:jdbc.properties</value></list></property></bean>注意:这种⽅式下,如果你在spring-mvc.xml⽂件中有如下配置,则⼀定不能缺少下⾯的红⾊部分,关于它的作⽤以及原理,参见另⼀篇博客:<!-- 配置组件扫描,springmvc容器中只扫描Controller注解 --><context:component-scan base-package="com.hafiz.www" use-default-filters="false"><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan>⽅式2.使⽤注解的⽅式注⼊,主要⽤在java代码中使⽤注解注⼊properties⽂件中相应的value值<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean"><!-- 这⾥是PropertiesFactoryBean类,它也有个locations属性,也是接收⼀个数组,跟上⾯⼀样 --><property name="locations"><array><value>classpath:jdbc.properties</value></array></property></bean>⽅式3.使⽤util:properties标签进⾏暴露properties⽂件中的内容<util:properties id="propertiesReader" location="classpath:jdbc.properties"/>注意:使⽤上⾯这⾏配置,需要在spring-dao.xml⽂件的头部声明以下红⾊的部分<beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:context="/schema/context"xmlns:util="/schema/util"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.2.xsd/schema/context/schema/context/spring-context-3.2.xsd/schema/util /schema/util/spring-util.xsd">⽅式4.通过PropertyPlaceholderConfigurer在加载上下⽂的时候暴露properties到⾃定义⼦类的属性中以供程序中使⽤<bean id="propertyConfigurer" class="com.hafiz.www.util.PropertyConfigurer"><property name="ignoreUnresolvablePlaceholders" value="true"/><property name="ignoreResourceNotFound" value="true"/><property name="locations"><list><value>classpath:jdbc.properties</value></list></property></bean>⾃定义类PropertyConfigurer的声明如下:package com.hafiz.www.util;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;import java.util.Properties;/*** Desc:properties配置⽂件读取类* Created by hafiz.zhang on 2016/9/14.*/public class PropertyConfigurer extends PropertyPlaceholderConfigurer {private Properties props; // 存取properties配置⽂件key-value结果@Overrideprotected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)throws BeansException {super.processProperties(beanFactoryToProcess, props);this.props = props;}public String getProperty(String key){return this.props.getProperty(key);}public String getProperty(String key, String defaultValue) {return this.props.getProperty(key, defaultValue);}public Object setProperty(String key, String value) {return this.props.setProperty(key, value);}}使⽤⽅式:在需要使⽤的类中使⽤@Autowired注解注⼊即可。

java从properties文件中读取和写入属性

java从properties文件中读取和写入属性

102 {
103 props.store(getUrl(),"放入一对属性");
104 }
105 catch (IOException e)
106 {
107 e.printStackTrace();
108 } // 保存属性到普通文件
109 }
110
111 //同时写入多个属性到 configuration.properties文件中
66 * @param参数
68 * @return 结果
69 */
70 public static String getString(String name, String def)
71 {
72
String retval = null;
73
try
74
89 HashMap<String,String> map = new HashMap<String,String>();
90 for(String name:names)
91 {
92 map.put(name, props.getProperty(name));
93 }
94 return map;
129 {
130 System.out.println(ConfigUtil.getString("name"));
131 System.out.println(ConfigUtil.getString("name2","qwertyuiop"));
132 setValue("姓名", "李WEI123");
84

properties文件java用法

properties文件java用法

【主题】properties文件java用法介绍在Java开发中,properties文件是一种常见的配置文件格式,它通常用来存储键值对的配置信息。

在本文中,我将深入探讨properties文件在Java中的用法,包括读取、写入、使用和常见问题的解决方法。

通过本文的学习,你将能够全面了解properties文件在Java开发中的重要性和灵活性。

1. properties文件的基本概念在Java中,properties文件是一种简单的配置文件,通常以.key=value的形式存储配置信息。

它可以被用于各种用途,如国际化、设置参数、环境配置等。

在Java中,我们可以使用java.util.Properties类来操作properties文件,包括读取、写入和修改。

2. properties文件的读取与写入在Java中,我们可以使用Properties类的load和store方法来读取和写入properties文件。

通过load方法,我们可以将properties 文件中的配置信息加载到Properties对象中;而通过store方法,我们可以将Properties对象中的配置信息写入到properties文件中。

这种简单而直观的读取与写入方式使得properties文件在Java中被广泛应用。

3. properties文件的使用在Java开发中,properties文件可以用于各种情境。

我们可以将数据库的连接信息、系统的参数配置、界面的文本信息等存储在properties文件中,从而实现配置与代码的分离,方便后期的维护和修改。

在国际化开发中,properties文件也扮演着重要的角色,我们可以通过不同的properties文件实现不同语言环境下的文本切换。

4. 常见问题及解决方法在使用properties文件的过程中,我们常常会遇到各种问题。

如何处理中文乱码问题、如何实现动态更新properties文件、如何处理properties文件中的注释等。

Java读写properties格式配置文件

Java读写properties格式配置文件

Java读写properties格式配置⽂件先贴⼀下格式1# Properties file with JDBC-related settings.2jdbc.driverClassName=com.mysql.jdbc.Driver3jdbc.url=连接地址ername=⽤户名5 jdbc.password=密码读写这种格式的配置⽂件,利⽤java.util.Properties类,此类的常⽤api如下:读⽰例:1import java.io.FileInputStream;2import java.io.FileNotFoundException;3import java.io.IOException;4import java.io.InputStream;5import java.util.Properties;6public class CH10Main {7public static void main(String[] args) {8 Properties test = new Properties();9try {10 InputStream input = new FileInputStream("resource/test.properties");11test.load(input);12 System.out.println(test.get("age"));13 } catch (FileNotFoundException e) {14// TODO Auto-generated catch block15e.printStackTrace();16 } catch (IOException e) {17// TODO Auto-generated catch block18e.printStackTrace();19}20}21 }写⽰例:1import java.io.FileNotFoundException;2import java.io.FileOutputStream;3import java.io.IOException;4import java.io.OutputStream;5import java.util.Properties;6public class CH10Main {7public static void main(String[] args) {8 Properties jdbc = new Properties();9 jdbc.put("url", "testurl");10 jdbc.put("username", "root");11 jdbc.put("password", "root");12try {13 OutputStream output = new FileOutputStream("resource/jdbc.properties");14 jdbc.store(output, "jdbc配置⽂件!");15 } catch (FileNotFoundException e) {16// TODO Auto-generated catch block17e.printStackTrace();18 } catch (IOException e) {19// TODO Auto-generated catch block20e.printStackTrace();21}22}23 }不过需要注意的是Java资源路径问题。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

java读写Properties属性文件公用方法
在Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。

在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。

Properties提供了如下几个主要的方法:
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 (),清除所有装载的键- 值对。

该方法在基类中提供。

以下提供一套读写配置文件的公用实用方法,我们以后可以在项目中进行引入。

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import org.apache.log4j.Logger;
public class PropertieUtil {
//设置日志
private static Logger logger=Logger.getLogger(PropertieUtil.class);
private PropertieUtil() {
}
/**
* 读取配置文件某属性
*/
public static String readValue(String filePath,String key) {
Properties props=new Properties();
try {
if(filePath.startsWith("/")) {
filePath="/"+filePath;
}
InputStream in=PropertieUtil.class.getResourceAsStream(filePath);
props.load(in);
String value=props.getProperty(key);
return value;
} catch (IOException e) {
// TODO Auto-generated catch block
logger.error(e);
return null;
}
}
/**
* 打印配置文件全部内容
*/
public static void readProperties(String filePath) {
Properties props=new Properties();
try {
if(!filePath.startsWith("/")) {
filePath="/"+filePath;
}
InputStream in=PropertieUtil.class.getResourceAsStream(filePath);
props.load(in);
Enumeration<?> en=props.propertyNames();
//遍历打印
while(en.hasMoreElements()) {
String key=(String)en.nextElement();
String property=props.getProperty(key);
//日志信息显示键和值
(key+":"+property);
}
}catch(Exception e) {
//日志显示错误信息
logger.error(e);
}
}
最后测试效果如下:
调用:readProperties("jdbc.properties");
调用writeProperties("test.properties","test","test");。

相关文档
最新文档