java读写Properties属性文件公用方法
java读写Properties属性文件公用方法
![java读写Properties属性文件公用方法](https://img.taocdn.com/s3/m/47329105650e52ea55189888.png)
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配置文件的读写](https://img.taocdn.com/s3/m/38d82c9482d049649b6648d7c1c708a1284a0a8a.png)
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配置文件方法总结](https://img.taocdn.com/s3/m/3ad7fa3c3868011ca300a6c30c2259010202f3a4.png)
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程序读取配置文件的几种方法](https://img.taocdn.com/s3/m/a46bfcd20d22590102020740be1e650e52eacf2d.png)
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文件内容不再是难题](https://img.taocdn.com/s3/m/4244952cabea998fcc22bcd126fff705cc175cf7.png)
五种⽅式让你在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文件中读取和写入属性](https://img.taocdn.com/s3/m/0b11b92c580102020740be1e650e52ea5518ceb0.png)
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用法](https://img.taocdn.com/s3/m/226c8c2e571252d380eb6294dd88d0d233d43c98.png)
【主题】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格式配置文件](https://img.taocdn.com/s3/m/16498cd609a1284ac850ad02de80d4d8d15a01fe.png)
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资源路径问题。
java如何读取properties文件
![java如何读取properties文件](https://img.taocdn.com/s3/m/0d83cac96e1aff00bed5b9f3f90f76c661374cf2.png)
java如何读取properties⽂件1.情景展⽰ 将要访问的接⼝地址等常⽤的配置添加到properties⽂件中,⽐直接写到java类中的好处在于: 当我们需要修改相应配置时,直接修改properties⽂件,重启tomcat即可,避免了重新编译引⽤该配置的java⽂件,同时,也便于项⽬的维护。
⽅式⼀ 通过spring的⼯具类PropertiesLoaderUtils来实现对properties⽂件的解析 所需jar包:spring的核⼼jar包,spring-core-版本号.jarimport java.io.IOException;import java.util.HashMap;import java.util.Map;import java.util.Properties;import org.springframework.core.io.support.PropertiesLoaderUtils;/*** 借助spring读取Properties⽂件* @explain Spring 提供的 PropertiesLoaderUtils* 允许您直接通过基于类路径的⽂件地址加载属性资源最⼤的好处就是:实时加载配置⽂件,修改后⽴即⽣效,不必重启* @author Marydon* @creationTime 2018年5⽉23⽇上午9:58:59* @version 1.0* @since* @email marydon20170307@*/public class PropertiesUtils {/*** 读取properties⽂件* @param fileName properties⽂件名及所在路径* @explain 参数说明* 1.传递的参数不是properties类型⽂件,不会报错,返回的是空Map;* 2.传递的参数是根本不存在的properties⽂件,也不会报错,返回的是空Map;* 3.传递的参数可以带路径,可以正常解析到* @return*/public static Map<String, String> readProperties(String fileName) {Map<String, String> resultMap = new HashMap<String, String>();try {Properties props = PropertiesLoaderUtils.loadAllProperties(fileName);for (Object key : props.keySet()) {resultMap.put(key.toString(), props.get(key).toString());}} catch (IOException e) {e.printStackTrace();}return resultMap;}/*** @param args*/public static void main(String[] args) {// Map map = readProperties("base/web/imageInfo/fileRootDirectories.properties");Map map = readProperties("fileRootDirectories.properties");for (Object key : map.keySet()) {System.out.println(key.toString() + "=" + map.get(key).toString());}// 打印结果// fileRootPath=uploadFiles}} 这种⽅式的缺点在于: 每次调⽤都要重新解析对应的properties⽂件,所以,我们可以在项⽬启动的时候,就把该⽂件加载到内存中(⼀次加载解析,永久使⽤)。
java读取properties文件的几种方法
![java读取properties文件的几种方法](https://img.taocdn.com/s3/m/2ebe3b1e4531b90d6c85ec3a87c24028915f85e5.png)
java读取properties⽂件的⼏种⽅法⼀、项⽬中经常会需要读取配置⽂件(properties⽂件),因此读取⽅法总结如下:1、通过java.util.Properties读取1 Properties p=new Properties();2//p需要InputStream对象进⾏读取⽂件,⽽获取InputStream有多种⽅法:3//1、通过绝对路径:InputStream is=new FileInputStream(filePath);4//2、通过Class.getResourceAsStream(path);5//3、通过ClassLoader.getResourceAsStream(path);6 p.load(InputStream is);7 is.close();8 p.getString(String(key))2、通过java.util.ResourceBundle读取ResourceBundle rb=ResourceBundle.getBundle(packageName);rb.getString(String key);⼆、Class.getResourceAsStream与ClassLoader.getResourceAsStream的区别⾸先,Java中的getResourceAsStream有以下⼏种:1. Class.getResourceAsStream(String path) : path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从ClassPath根下获取。
其只是通过path构造⼀个绝对路径,最终还是由 ClassLoader获取资源。
2. Class.getClassLoader.getResourceAsStream(String path) :默认则是从ClassPath根下获取,path不能以’/'开头,最终是由ClassLoader 获取资源。
Java读取.properties配置文件的几种方式
![Java读取.properties配置文件的几种方式](https://img.taocdn.com/s3/m/047c680715791711cc7931b765ce05087632752e.png)
Java读取.properties配置⽂件的⼏种⽅式Java 开发中,需要将⼀些易变的配置参数放置再 XML 配置⽂件或者 properties 配置⽂件中。
然⽽ XML 配置⽂件需要通过DOM 或 SAX ⽅式解析,⽽读取 properties 配置⽂件就⽐较容易。
介绍⼏种读取⽅式:1、基于ClassLoder读取配置⽂件注意:该⽅式只能读取类路径下的配置⽂件,有局限但是如果配置⽂件在类路径下⽐较⽅便。
Properties properties = new Properties();// 使⽤ClassLoader加载properties配置⽂件⽣成对应的输⼊流InputStream in = PropertiesMain.class.getClassLoader().getResourceAsStream("config/config.properties");// 使⽤properties对象加载输⼊流properties.load(in);//获取key对应的value值properties.getProperty(String key);2、基于 InputStream 读取配置⽂件注意:该⽅式的优点在于可以读取任意路径下的配置⽂件Properties properties = new Properties();// 使⽤InPutStream流读取properties⽂件BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/config.properties"));properties.load(bufferedReader);// 获取key对应的value值properties.getProperty(String key);3、通过 java.util.ResourceBundle 类来读取,这种⽅式⽐使⽤ Properties 要⽅便⼀些1>通过 ResourceBundle.getBundle() 静态⽅法来获取(ResourceBundle是⼀个抽象类),这种⽅式来获取properties属性⽂件不需要加.properties后缀名,只需要⽂件名即可 properties.getProperty(String key);//config为属性⽂件名,放在包com.test.config下,如果是放在src下,直接⽤config即可ResourceBundle resource = ResourceBundle.getBundle("com/test/config/config");String key = resource.getString("keyWord");2>从 InputStream 中读取,获取 InputStream 的⽅法和上⾯⼀样,不再赘述ResourceBundle resource = new PropertyResourceBundle(inStream);注意:在使⽤中遇到的最⼤的问题可能是配置⽂件的路径问题,如果配置⽂件⼊在当前类所在的包下,那么需要使⽤包名限定,如:config.properties⼊在com.test.config包下,则要使⽤com/test/config/config.properties(通过Properties来获取)或com/test/config/config(通过ResourceBundle来获取);属性⽂件在src根⽬录下,则直接使⽤config.properties或config即可。
JAVA读取PROPERTIES文件方式一
![JAVA读取PROPERTIES文件方式一](https://img.taocdn.com/s3/m/b2752aecc9d376eeaeaad1f34693daef5ef71303.png)
JAVA读取PROPERTIES⽂件⽅式⼀ 1import java.io.BufferedReader;2import java.io.IOException;3import java.io.InputStream;4import java.io.InputStreamReader;5import java.util.Properties;67import mons.logging.Log;8import mons.logging.LogFactory;910/**11 * 配置⽂件读取⼯具12*/13public class ConfigurableConstants14 {1516protected static final String PROPERTIES_PATH = "config.properties";1718protected static Log logger = LogFactory.getLog(ConfigurableConstants.class);19protected static Properties p = new Properties();20static21 {22 init(PROPERTIES_PATH);23 }2425/**26 * 静态读⼊属性⽂件到Properties p变量中27*/28protected static void init(String propertyFileName)29 {30 InputStream in = null;31try32 {33// class.getClassLoader()获得该class⽂件加载的web应⽤的⽬录,如WEB-INF/classes/就是根⽬录34// getResourceAsStream(relativeFilePath):定位该⽂件且获得它的输出流35 in = ConfigurableConstants.class.getClassLoader().getResourceAsStream(propertyFileName);36 BufferedReader bf = null;37if (in != null)38// load输出流到Properties对象中39// 因为字节流是⽆法读取中⽂的,所以采取reader把inputStream转换成reader⽤字符流来读取中⽂。
Java中的几种读取properties配置文件的方式
![Java中的几种读取properties配置文件的方式](https://img.taocdn.com/s3/m/b8959748bf23482fb4daa58da0116c175f0e1e0e.png)
Java中的⼏种读取properties配置⽂件的⽅式相信对于⼀名JAVA开发者开说properties⽂件⼀定再熟悉不过了,⽐如⼀下配置:1. config.properties会经常存放⼀些系统常量,版本号,路径之类的2. database.properties存放数据库的连接参数3. log4j.properties ⽇志的⼀些基本配置4. redis.properties 缓存数据库的⼀些配置当然前缀是根据⽤能⾃⾏定义的,⼀般来说⽂件的内容的格式是“键=值”的格式,⽂本注释信息可以⽤”#”来注释,下⾯来说说开发中如何读写properties配置⽂件。
Java读取Properties⽂件Properties类读取Properties类继承⾃Hashtable类并且实现了Map接⼝,也是使⽤⼀种键值对的形式来保存属性集。
不过Properties有特殊的地⽅,就是它的键和值都是字符串类型。
//⽅式⼀InputStream in = new BufferedInputStream(new FileInputStream("⽂件路径名"));Properties p = new Properties();p.load(in);System.out.println(p.getProperty("version"));//⽅式⼆InputStream ins = PropertiesUtil.class.getResourceAsStream("⽂件路径名");Properties ps = new Properties();ps.load(ins);System.out.println(ps.getProperty("version"));//⽅式三InputStream inss = PropertiesUtil.class.getClassLoader().getResourceAsStream("⽂件名");Properties pss = new Properties();pss.load(inss);System.out.println(pss.getProperty("version"));//⽅式四InputStream insss = ClassLoader.getSystemResourceAsStream("⽂件名");Properties psss = new Properties();psss.load(insss);System.out.println(pss.getProperty("version"));ResourceBundle读取⽅式这个类提供软件国际化的捷径。
读取properties四种方式
![读取properties四种方式](https://img.taocdn.com/s3/m/a62f16fcbb0d4a7302768e9951e79b896802689a.png)
读取properties四种⽅式前⾔在项⽬开发中经常会⽤到配置⽂件,配置⽂件的存在解决了很⼤⼀份重复的⼯作。
今天就分享四种在Springboot中获取配置⽂件的⽅式。
注:前三种测试配置⽂件为springboot默认的application.properties⽂件[html]1. #######################⽅式⼀#########################2. com.battle.type3=Springboot - @ConfigurationProperties3. com.battle.title3=使⽤@ConfigurationProperties获取配置⽂件4. #map5. com.battle.login[username]=admin6. com.battle.login[password]=1234567. com.battle.login[callback]=8. #list9. com.battle.urls[0]=10. com.battle.urls[1]=/format/js11. com.battle.urls[2]=/str2image12. com.battle.urls[3]=/json2Entity13. com.battle.urls[4]=/ua14.15. #######################⽅式⼆#########################16. com.battle.type=Springboot - @Value17. com.battle.title=使⽤@Value获取配置⽂件18.19. #######################⽅式三#########################20. com.battle.type2=Springboot - Environment21. com.battle.title2=使⽤Environment获取配置⽂件⼀、@ConfigurationProperties⽅式⾃定义配置类:PropertiesConfig.java[java]1. import java.io.UnsupportedEncodingException;2. import java.util.ArrayList;3. import java.util.HashMap;4. import java.util.List;5. import java.util.Map;6. import org.springframework.boot.context.properties.ConfigurationProperties;7. //import org.springframework.context.annotation.PropertySource;8. import ponent;9. /**10. * 对应上⽅配置⽂件中的第⼀段配置11. * @author battle12. * @date 2017年6⽉1⽇下午4:34:1813. * @version V1.014. * @since JDK : 1.7 */15. @Component16. @ConfigurationProperties(prefix = "com.zyd")17. // PropertySource默认取application.properties18. // @PropertySource(value = "config.properties")19. public class PropertiesConfig {20. public String type3; public String title3;21. public Map<String, String> login = new HashMap<String, String>();22. public List<String> urls = new ArrayList<>();23. public String getType3() {24. return type3;25. }26. public void setType3(String type3) {27. this.type3 = type3;28. }29. public String getTitle3() {30. try {31. return new String(title3.getBytes("ISO-8859-1"), "UTF-8");32. } catch (UnsupportedEncodingException e) {33. e.printStackTrace();34. }35. return title3;36. }37. public void setTitle3(String title3) {38. this.title3 = title3;39. }40. public Map<String, String> getLogin() { return login; }41. public void setLogin(Map<String, String> login) { this.login = login; }42. public List<String> getUrls() { return urls; }43. public void setUrls(List<String> urls) { this.urls = urls; } }程序启动类:Applaction.java[java]1. import java.io.UnsupportedEncodingException;2. import java.util.HashMap;3. import java.util.Map;4. import org.springframework.beans.factory.annotation.Autowired;5. import org.springframework.boot.SpringApplication;6. import org.springframework.boot.autoconfigure.SpringBootApplication;7. import org.springframework.web.bind.annotation.RequestMapping;8. import org.springframework.web.bind.annotation.RestController;9. import com.zyd.property.config.PropertiesConfig;10. @SpringBootApplication11. @RestController12. public class Applaction {13. @Autowired private PropertiesConfig propertiesConfig;14. /**15. * 第⼀种⽅式:使⽤`@ConfigurationProperties`注解将配置⽂件属性注⼊到配置对象类中16. * @throws UnsupportedEncodingException17. * @since JDK 1.7 */18. @RequestMapping( "/config" ) public Map<String, Object> configurationProperties()19. {20. Map<String, Object> map = new HashMap<String, Object>();21. map.put( "type", propertiesConfig.getType3() );22. map.put( "title", propertiesConfig.getTitle3() );23. map.put( "login", propertiesConfig.getLogin() );24. map.put( "urls", propertiesConfig.getUrls() );25. return(map);26. }27. public static void main( String[] args ) throws Exception28. {29. SpringApplication application = new SpringApplication( Applaction.class );30. application.run( args );31. }32. }访问结果:{"title":"使⽤@ConfigurationProperties获取配置⽂件","urls":["","/format/js","/str2image","/json2Entity","/ua"],"login":{"username":"admin","callback":"","password":"123456"},"type":"Springboot - @ConfigurationProperties"}⼆、使⽤@Value注解⽅式程序启动类:Applaction.java[java]1. import java.io.UnsupportedEncodingException;2. import java.util.HashMap;3. import java.util.Map;4. import org.springframework.beans.factory.annotation.Value;5. import org.springframework.boot.SpringApplication;6. import org.springframework.boot.autoconfigure.SpringBootApplication;7. import org.springframework.web.bind.annotation.RequestMapping;8. import org.springframework.web.bind.annotation.RestController;9. @SpringBootApplication10. @RestController11. public class Applaction {12. @Value("${com.zyd.type}") private String type;13. @Value("${com.zyd.title}") private String title;14. /** * * 第⼆种⽅式:使⽤`@Value("${propertyName}")`注解 *15. * @throws UnsupportedEncodingException * @since JDK 1.7 */16. @RequestMapping("/value") public Map<String, Object> value() throws UnsupportedEncodingException {17. Map<String, Object> map = new HashMap<String, Object>();18. map.put("type", type);19. // *.properties⽂件中的中⽂默认以ISO-8859-1⽅式编码,因此需要对中⽂内容进⾏重新编码20. map.put("title", new String(title.getBytes("ISO-8859-1"), "UTF-8"));21. return map;22. }23. public static void main(String[] args) throws Exception {24. SpringApplication application = new SpringApplication(Applaction.class);25. application.run(args);26. } }访问结果:{"title":"使⽤@Value获取配置⽂件","type":"Springboot - @Value"}三、使⽤Environment程序启动类:Applaction.java[java]1. import java.io.UnsupportedEncodingException;2. import java.util.HashMap;3. import java.util.Map;4. import org.springframework.beans.factory.annotation.Autowired;5. import org.springframework.boot.SpringApplication;6. import org.springframework.boot.autoconfigure.SpringBootApplication;7. import org.springframework.core.env.Environment;8. import org.springframework.web.bind.annotation.RequestMapping;9. import org.springframework.web.bind.annotation.RestController;10.11. @SpringBootApplication12. @RestController13. public class Applaction {14. @Autowired private Environment env;15. /** * * 第三种⽅式:使⽤`Environment` * * @author zyd * @throws UnsupportedEncodingException * @since JDK 1.7 */16. @RequestMapping("/env") public Map<String, Object> env() throws UnsupportedEncodingException {17. Map<String, Object> map = new HashMap<String, Object>();18. map.put("type", env.getProperty("com.zyd.type2"));19. map.put("title", new String(env.getProperty("com.zyd.title2").getBytes("ISO-8859-1"), "UTF-8"));20. return map;21. }22. public static void main(String[] args) throws Exception {23. SpringApplication application = new SpringApplication(Applaction.class);24. application.run(args);25. }26. }访问结果:{"title":"使⽤Environment获取配置⽂件","type":"Springboot - Environment"}四、使⽤PropertiesLoaderUtilsapp-config.properties[html]1. #### 通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的⽅式2. com.battle.type=Springboot - Listeners3. com.battle.title=使⽤Listeners + PropertiesLoaderUtils获取配置⽂件4. =zyd5. com.battle.address=Beijing6. pany=inPropertiesListener.java ⽤来初始化加载配置⽂件[java]1. import org.springframework.boot.context.event.ApplicationStartedEvent;2. import org.springframework.context.ApplicationListener;3. import com.zyd.property.config.PropertiesListenerConfig;4. public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {5. private String propertyFileName;6. public PropertiesListener(String propertyFileName) {7. this.propertyFileName = propertyFileName;8. }9. @Override public void onApplicationEvent(ApplicationStartedEvent event) {10. PropertiesListenerConfig.loadAllProperties(propertyFileName);11. }12. }PropertiesListenerConfig.java 加载配置⽂件内容[java]1. import org.springframework.boot.context.event.ApplicationStartedEvent;2. import org.springframework.context.ApplicationListener;3. import com.zyd.property.config.PropertiesListenerConfig;4. public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {5. private String propertyFileName;6. public PropertiesListener(String propertyFileName) {7. this.propertyFileName = propertyFileName;8. }9. @Override public void onApplicationEvent(ApplicationStartedEvent event) {10. PropertiesListenerConfig.loadAllProperties(propertyFileName);11. }12. }Applaction.java 启动类[java]1. import java.io.UnsupportedEncodingException;2. import java.util.HashMap;3. import java.util.Map;4. import org.springframework.boot.SpringApplication;5. import org.springframework.boot.autoconfigure.SpringBootApplication;6. import org.springframework.web.bind.annotation.RequestMapping;7. import org.springframework.web.bind.annotation.RestController;8. import com.zyd.property.config.PropertiesListenerConfig;9. import com.zyd.property.listener.PropertiesListener;10.11. @SpringBootApplication @RestController public class Applaction {12. /** * * 第四种⽅式:通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的⽅式 * * @author zyd * @throws UnsupportedEncodingException * @since JDK 1.7 */13. @RequestMapping("/listener") public Map<String, Object> listener() {14. Map<String, Object> map = new HashMap<String, Object>();15. map.putAll(PropertiesListenerConfig.getAllProperty());16. return map;17. }18. public static void main(String[] args) throws Exception {19. SpringApplication application = new SpringApplication(Applaction.class);20. // 第四种⽅式:注册监听器 application.addListeners(new PropertiesListener("app-config.properties")); application.run(args); } } 访问结果:[java]1. {"":"zyd",2. "com.battle.address":"Beijing",3. "com.battle.title":"使⽤Listeners + PropertiesLoaderUtils获取配置⽂件",4. "com.battle.type":"Springboot - Listeners",5. "pany":"in"}。
Java读取Properties文件的六种方法
![Java读取Properties文件的六种方法](https://img.taocdn.com/s3/m/b89b3da3b0717fd5360cdc6d.png)
返回rb.getLocale();
}
公共对象的GetObject(String键){
返回rb.getObject(关键);
}
公共字符串的getString(String键){
返回rb.getString(关键);
}
名称=“\ \的COM \ \ kindani \ \测试\ \ LocalStrings.properties”;
P值JProperties.loadProperties(姓名,JProperties.BY_SYSTEM_CLASSLOADER);
Properties p = new Properties();
InputStream in = null;
if (type == BY_PROPERTIES) {
in = new BufferedInputStream(new FileInputStream(name));
}否则如果(类型== BY_CLASSLOADER){
断言(JProperties.class.getClassLoader()。等于(新JProperties()。的getClass()。getClassLoader ()));
。在= JProperties.class.getClassLoader()getResourceAsStream(姓名);
assert (in != null);
ResourceBundle rb = new PropertyResourceBundle(in);
p = new ResourceBundleAdapter(rb);
} else if (type == BY_CLASS) {
读取properties配置文件的方法
![读取properties配置文件的方法](https://img.taocdn.com/s3/m/3cfee29a0129bd64783e0912a216147917117e35.png)
读取properties配置文件的方法读取properties配置文件的方法有多种,下面列举两种常见的方法:方法一:使用Java的Properties类1. 创建一个Properties对象2. 使用load()方法加载配置文件3. 使用getProperty()方法获取配置项的值示例代码如下:```import java.io.FileInputStream;import java.util.Properties;public class ReadPropertiesFile {public static void main(String[] args) {try {//创建一个Properties对象Properties properties = new Properties();//加载配置文件FileInputStream file = newFileInputStream("config.properties");properties.load(file);//获取配置项的值String value = properties.getProperty("key");System.out.println("Value: " + value);file.close();} catch (Exception e) {e.printStackTrace();}}}```方法二:使用Spring的PropertyPlaceholderConfigurer类1. 在Spring配置文件中引入PropertyPlaceholderConfigurer类2. 配置properties文件的位置和文件名3. 使用${key}的形式获取配置项的值示例代码如下:```importorg.springframework.beans.factory.config.PropertyPlaceholderCon figurer;importorg.springframework.context.support.ClassPathXmlApplicationCo ntext;public class ReadPropertiesFile {public static void main(String[] args) {try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml")) { //获取配置项的值String value =context.getEnvironment().getProperty("key");System.out.println("Value: " + value);} catch (Exception e) {e.printStackTrace();}}}```注意:需要将配置文件(config.properties)放置在项目的根目录或者resources目录下。
java读取properties文件总结
![java读取properties文件总结](https://img.taocdn.com/s3/m/9b211ac726fff705cc170a1c.png)
java读取properties文件总结一、java读取properties文件总结在java项目中,操作properties文件是经常要做的,因为很多的配置信息都会写在properties文件中,这里主要是总结使用getResourceAsStream方法和InputStream流去读取properties文件,使用getResourceAsStream方法去读取properties文件时需要特别注意properties文件路径的写法,测试项目如下:1.1.项目的目录结构1.2. java读取properties文件代码测试复制代码/* 范例名称:java读取properties文件总结* 源文件名称:PropertiesFileReadTest.java* 要点:* 1. 使用getResourceAsStream方法读取properties文件* 2. 使用InPutStream流读取properties文件* 3. 读取properties文件的路径写法问题* 时间:2014/4/2*/package propertiesFile.read.test;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.text.MessageFormat;import java.util.Properties;public class PropertiesFileReadTest {/*** @param args*/public static void main(String[] args) {try {readPropFileByGetResourceAsStream();System.out.println("");readPropFileByInPutStream();} catch (Exception e) {e.printStackTrace();// TODO: handle exception}}/*** 使用getResourceAsStream方法读取properties文件*/static void readPropFileByGetResourceAsStream() {/*** 读取src下面config.properties包内的配置文件* test1.properties位于config.properties包内*/InputStream in1 = PropertiesFileReadTest.class.getClassLoader().getResourceAsStream("config/properties/test1.properties");/*** 读取和PropertiesFileReadTest类位于同一个包里面的配置文件* test2.properties和PropertiesFileReadTest类在同一个包里面*/InputStream in2 = PropertiesFileReadTest.class.getResourceAsStream("test2.properties");/*** 读取src根目录下文件的配置文件* jdbc.properties位于src目录*/InputStream in3 = PropertiesFileReadTest.class.getClassLoader().getResourceAsStream("jdbc.properties");/*** 读取位于另一个source文件夹里面的配置文件* config是一个source文件夹,config.properties位于config source文件夹中*/InputStream in4 = PropertiesFileReadTest.class.getClassLoader().getResourceAsStream("config.properties");Properties p = new Properties();System.out.println("----使用getResourceAsStream方法读取properties文件----");try {System.out.println("----------------------------------------------");p.load(in1);System.out.println("test1.properties:name=" + p.getProperty("name")+ ",age=" + p.getProperty("age"));System.out.println("----------------------------------------------");p.load(in2);System.out.println("test2.properties:name=" + p.getProperty("name") + ",age=" + p.getProperty("age"));System.out.println("----------------------------------------------");p.load(in3);System.out.println("jdbc.properties:");System.out.println(String.format("jdbc.driver=%s",p.getProperty("jdbc.driver")));// 这里的%s是java String占位符System.out.println(String.format("jdbc.url=%s",p.getProperty ("jdbc.url")));System.out.println(String.format("ename=%s",p.getProperty("ename")));System.out.println(String.format("jdbc.password=%s",p.getProperty("jdbc.password")));System.out.println("----------------------------------------------");p.load(in4);System.out.println("config.properties:");System.out.println(MessageFormat.format("dbuser={0}",p.getProperty("dbuser")));// {0}是一个java的字符串占位符System.out.println(MessageFormat.format("dbpassword={0}",p.getProperty("dbpassword")));System.out.println(MessageFormat.format("database={0}",p.getProperty("database")));System.out.println("----------------------------------------------");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (in1 != null) {try {in1.close();} catch (IOException e) {e.printStackTrace();}}if (in2 != null) {try {in2.close();} catch (IOException e) {e.printStackTrace();}}if (in3 != null) {try {in3.close();} catch (IOException e) {e.printStackTrace();}}if (in4 != null) {try {in4.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 使用InPutStream流读取properties文件*/static void readPropFileByInPutStream() {InputStream in1 = null;InputStream in2 = null;InputStream in3 = null;InputStream in4 = null;System.out.println("----使用InputStream流读取properties文件----");try {/*** 读取src根目录下文件的配置文件* jdbc.properties位于src目录*/in1 = new BufferedInputStream(new FileInputStream("src/jdbc.properties"));/*** 读取src下面config.properties包内的配置文件* test1.properties位于config.properties包内*/in2 = new BufferedInputStream(new FileInputStream("src/config/properties/test1.properties"));/*** 读取和PropertiesFileReadTest类位于同一个包里面的配置文件* test2.properties和PropertiesFileReadTest类在同一个包里面*/in3 = new BufferedInputStream(new FileInputStream("src/propertiesFile/read/test/test2.properties"));/*** 读取位于另一个source文件夹里面的配置文件* config是一个source文件夹,config.properties位于config source文件夹中*/in4 = new FileInputStream("config/config.properties");Properties p = new Properties();System.out.println("----------------------------------------------");p.load(in1);System.out.println("jdbc.properties:");System.out.println(String.format("jdbc.driver=%s",p.getProperty("jdbc.driver")));// 这里的%s是java String占位符System.out.println(String.format("jdbc.url=%s",p.getProperty("jdbc.url")));System.out.println(String.format("ename=%s",p.getProperty("ename")));System.out.println(String.format("jdbc.password=%s",p.getProperty("jdbc.password")));System.out.println("----------------------------------------------");p.load(in2);System.out.println("test1.properties:name=" + p.getProperty("name")+ ",age=" + p.getProperty("age"));System.out.println("----------------------------------------------");p.load(in3);System.out.println("test2.properties:name=" + p.getProperty("name")+ ",age=" + p.getProperty("age"));System.out.println("----------------------------------------------");p.load(in4);System.out.println("config.properties:");System.out.println(MessageFormat.format("dbuser={0}",p.getProperty("dbuser")));// {0}是一个java的字符串占位符System.out.println(MessageFormat.format("dbpassword={0}",p.getProperty("dbpassword")));System.out.println(MessageFormat.format("database={0}",p.getProperty("database")));System.out.println("----------------------------------------------");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (in1 != null) {try {in1.close();} catch (IOException e) {e.printStackTrace();}}if (in2 != null) {try {in2.close();} catch (IOException e) {e.printStackTrace();}}if (in3 != null) {try {in3.close();} catch (IOException e) {e.printStackTrace();}}if (in4 != null) {try {in4.close();} catch (IOException e) {e.printStackTrace();}}}}}。
java用类加载器的5种方式读取.properties文件
![java用类加载器的5种方式读取.properties文件](https://img.taocdn.com/s3/m/fb64a014eef9aef8941ea76e58fafab069dc4434.png)
java⽤类加载器的5种⽅式读取.properties⽂件⽤类加载器的5中形式读取.properties⽂件(这个.properties⽂件⼀般放在src的下⾯)⽤类加载器进⾏读取:这⾥采取先向⼤家讲读取类加载器的⼏种⽅法;然后写⼀个例⼦把⼏种⽅法融进去,让⼤家直观感受。
最后分析原理。
(主要是结合所牵涉的⽅法的源代码的⾓度进⾏分析)这⾥先介绍⽤类加载器读取的⼏种⽅法:1.任意类名.class.getResourceAsStream("/⽂件所在的位置");【⽂件所在的位置从包名开始写】2.和.properties⽂件在同⼀个⽬录下的类名.class.getResourceAsStream("⽂件所在的位置");【⽂件所在的位置从包名开始写,注意这⾥和上⾯的相⽐较少了⼀个斜杠/】 当然你也可以写成跟1⼀样的形式即:任意类名.class.getResourceAsStream("/⽂件所在的位置");3.任意类名.class.getClassLoader().getResourceAsStream("⽂件所在的位置");【⽂件所在的位置从包名开始写】4.任意类名.class.getClassLoader().getResource("⽂件所在的位置").openStream();【⽂件所在的位置从包名开始写】5.任意类名.class.getClassLoader().getResource("⽂件所在的位置")..openConnection().getInputStream();【⽂件所在的位置从包名开始写】//⼀个例⼦,说明上述5中⽅法的⽤法。
上⾯图⽚中的各个红⾊矩形就是我要读取的properties⽂件。
主要是两类。
⼀类直接放在src下⾯。
另⼀类是放在某个⽂件夹下⾯.//f.properties⽂件的内容如下图所⽰;//上述五种情况说明的代码如下:package monclass;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import com.qls.counter.Ok;/*** 分别⽤类加载器的5种⽅法读取f.properties⽂件。
Java:IONIO篇,读写属性文件(properties)
![Java:IONIO篇,读写属性文件(properties)](https://img.taocdn.com/s3/m/99eae0c6c0c708a1284ac850ad02de80d4d806cc.png)
Java:IONIO篇,读写属性⽂件(properties)1. 描述尝试⽤多种⽅法读取属性⽂件。
1. 测试打印系统属性;2. 测试读取、写⼊⽤户属性⽂件;3. 测试读取类库中的属性⽂件。
2. ⽰范代码package com.clzhang.sample.io;import java.io.*;import java.util.*;import org.junit.Test;/*** 属性⽂件测试类,* 1.测试打印系统属性;* 2.测试读取、写⼊⽤户属性⽂件;* 3.测试读取类库中的属性⽂件。
* @author Administrator**/public class PropertyTest {@SuppressWarnings("rawtypes")@Testpublic void testProp() throws Exception {// 打印系统属性Properties propSystem = System.getProperties();System.out.println("-------------------------");for (Enumeration e = propSystem.propertyNames(); e.hasMoreElements();) {String key = (String) e.nextElement();System.out.println(key + "=" + propSystem.getProperty(key));}System.out.println("-------------------------");// ⽅式⼀,硬编码指定属性⽂件位置// String filename = "C:\\solr\\collection1\\conf\\prop.properties";// ⽅式⼆,相对路径指定属性⽂件String filename = "prop.properties";File file = new File(filename);if(!file.exists()) {System.out.println("在⽤户默认⽬录:" + propSystem.get("user.dir") + "下⾯找不到:" + file.getName() + "⽂件!");}else {// 读取属性配置⽂件Properties prop = new Properties();FileInputStream fis = new FileInputStream(file);prop.load(fis);fis.close();// 读取属性值System.out.println("log4j.appender.R=" + prop.getProperty("log4j.appender.R"));System.out.println("does_not_exist_node=" + prop.getProperty("dose_not_exist_node", "Hello"));// 更改属性值prop.setProperty("log4j.appender.R", "你想怎样");prop.setProperty("add_node", "Hello There!");// 保存到⽂件FileOutputStream fos = new FileOutputStream(filename);prop.store(fos, "a description of the property list");fos.close();System.out.println("-------------------------");}// ⽅式三,系统类库中查找属性⽂件String propFileInJar = "com/clzhang/sample/io/prop.properties";InputStream is = this.getClass().getClassLoader().getResourceAsStream(propFileInJar);// 上⾯⼆⾏代码等同于下⾯⼆⾏任⼀⾏代码// 相对路径// InputStream is = com.clzhang.sample.io.PropertyTest.class.getResourceAsStream("prop.properties");// 绝对路径// InputStream is = com.clzhang.sample.io.PropertyTest.class.getResourceAsStream("/com/clzhang/sample/io/prop.properties");if(is == null) {System.out.println("在系统类库中没有找到:" + propFileInJar + "⽂件!");System.out.println("类路径:" + propSystem.get("java.class.path"));}else {Properties prop = new Properties();prop.load(is);is.close();System.out.println("log4j.appender.R=" + prop.getProperty("log4j.appender.R")); System.out.println("-------------------------");}}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 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");。