如何读取properties文件中属性

来源:互联网 发布:不需要网络的电脑游戏 编辑:程序博客网 时间:2024/05/16 13:42

在现实工作中,我们常常需要保存一些系统配置信息,大家一般都会选择配置文件来完成,本文根据我工作中用到的读取properties配置文件的方法小小总结一下,主要叙述的是spring读取配置文件的方法。
用spring读取配置文件,最典型的就是关于数据库的连接,下面就是一个例子:
文件database.properties:
-------------------------------------------------------------------------------------
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/zjgxm?charset=utf-8
jdbc.username=root
jdbc.password=111111

#<!-- 初始化连接 -->
dataSource.initialSize=5
#<!-- 最大空闲连接 0为最大 -->
dataSource.maxIdle=0
#<!-- 最小空闲连接 -->
dataSource.minIdle=5
#最大连接数量
dataSource.maxActive=50
#是否在自动回收超时连接的时候打印连接的超时错误
dataSource.logAbandoned=true
#是否自动回收超时连接
dataSource.removeAbandoned=true
#超时时间(以秒数为单位)
dataSource.removeAbandonedTimeout=180
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
dataSource.maxWait=1000
------------------------------------------------------------------------------------
引入spring的相关jar包,在applicationContext.xml中配置:
-------------------------------------------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:aop="http://www.springframework.org/schema/aop"        xmlns:tx="http://www.springframework.org/schema/tx"       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd    http://www.springframework.org/schema/tx    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="locations">            <value>classpath:database.properties</value>        </property>    </bean>        <bean id="dataSource" destroy-method="close"          class="org.apache.commons.dbcp.BasicDataSource">        <property name="driverClassName" value="${jdbc.driverClassName}"/>        <property name="url" value="${jdbc.url}"/>        <property name="username" value="${jdbc.username}"/>        <property name="password" value="${jdbc.password}"/>                <property name="initialSize" value="${dataSource.initialSize}"/>        <property name="maxIdle" value="${dataSource.maxIdle}"/>        <property name="minIdle" value="${dataSource.minIdle}"/>        <property name="maxActive" value="${dataSource.maxActive}"/>        <property name="logAbandoned" value="${dataSource.logAbandoned}"/>        <property name="removeAbandoned" value="${dataSource.removeAbandoned}"/>        <property name="removeAbandonedTimeout" value="${dataSource.removeAbandonedTimeout}"/>        <property name="maxWait" value="${dataSource.maxWait}"/>    </bean>        <import resource="spring-conf/spring-admin.xml"/>    </beans>

 
-----------------------------------------------------------------------------------------
DataDAO.java

package com.zh.model;

import javax.sql.DataSource;

public class DataDAO {
private DataSource datasource;

public DataSource getDatasource() {
return datasource;
}

public void setDatasource(DataSource datasource) {
this.datasource = datasource;
}

}
------------------------------------------------------------------------------------
测试连接是否成功,test.java
package com.zh.logic;

import java.sql.Connection;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.zh.model.DataDAO;

public class test {
public static void main(String [] args){
try{
String[] path = {"spring.xml"};
ApplicationContext ctx = new FileSystemXmlApplicationContext(path);

DataDAO dao = (DataDAO)ctx.getBean("dao");
Connection con = dao.getDatasource().getConnection();
System.out.println(con.isClosed());
//System.out.print(dao.getName());
}catch(Exception ex){
ex.printStackTrace();
}
}
}
-------------------------------------------------------------------------------------
2.用java.util.Properties这个类来读取
比如,我们构造一个ipConfig.properties来保存服务器ip地址和端口,如:
ip=192.168.0.1
port=8080
--------------------------------------------------------------------------------------
则,我们可以用如下程序来获得服务器配置信息:
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("database.properties");
Properties p = new Properties();
try{
p.load(inputStream);
} catch (IOException e1){
e1.printStackTrace();
}
System.out.println("url:"+p.getProperty("jdbc.url")+"username"+p.getProperty("jdbc.username"));
--------------------------------------------------------------------------------------
上面介绍了读取properties的内容,现实中我们还有可能要修改文件的内容,下面就看下怎么修改properties的内容,文件还是上面那个:
package com.zh.logic;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;

public class TestRead {

public void read(){
try {
InputStream in = this.getClass().getClassLoader().getResourceAsStream("config/host.properties");
Properties p = new Properties();
p.load(in);
//p.list(System.out);

System.out.println(p.getProperty("ip")+","+p.getProperty("username")+","+p.getProperty("pwd"));
} catch (Exception e) {
e.printStackTrace();
}
}

public void update(String path){
try{
Properties p = new Properties();
FileInputStream in = new FileInputStream(path);
p.load(in);
FileOutputStream out = new FileOutputStream(path);

p.setProperty("ip","1234567");
p.store(out,"ip update");
//p.save(out,"ip updated");
}catch(Exception ex){
ex.printStackTrace();
}
}
public static void main(String[] args){
TestRead td = new TestRead();
td.read();
td.update("config/host.properties");
td.read();
}
}
可以看见修改之前的和修改之后的内容有改变;在上面有点要注意的:
FileInputStream in = new FileInputStream(path);
p.load(in);
FileOutputStream out = new FileOutputStream(path);
就是p.load(in);要写在FileOutputStream out = new FileOutputStream(path);之前,不然的话,修改后的文件内容就成了ip=1234567,而port=8080这句被覆盖了;

 

方法3:

package com.util;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;public class DBUtil {public static void main(String[] args){   DBUtil db = new DBUtil();   db.readProperties();    }public void readProperties(){   try {    Properties props = new Properties();    //第一种读取 properties 方法    props.load(getClass().getResourceAsStream("/config/oracleConn.properties"));           //-------------------------------------------------------------    //读取键值    String oracle_url = props.getProperty("oracle_url");    String oracle_name = props.getProperty("oracle_name");    String oracle_user = props.getProperty("oracle_user");    String oracle_pwd = props.getProperty("oracle_pwd");       Class.forName("oracle.jdbc.driver.OracleDriver"); //加载oracle驱动    Connection conn = DriverManager.getConnection(oracle_url,oracle_user,oracle_pwd);    System.out.println(conn);       conn.close();   } catch (FileNotFoundException e) {    e.printStackTrace();   } catch (IOException e) {    e.printStackTrace();   } catch (ClassNotFoundException e) {    e.printStackTrace();   } catch (SQLException e) {    e.printStackTrace();   }}}

 

 

 

 

引自:http://hi.baidu.com/alizv/item/358543e1b6ad2df32a09a426

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 文曲星放太久开不了机怎么办 小狗吃火腿肠皮怎么办 虚火引起的牙痛怎么办 牙髓炎怎么办立刻止疼 小蜜丸吃不下去怎么办 铜钱的字不认识怎么办 古钱币出手好烦怎么办 安装目录不可写怎么办 手机不支持exfat格式怎么办 windows7图标变大了怎么办 igs格式烂曲面怎么办 手机桌面文件夹打不开怎么办 苹果下载不了150怎么办 iphone6速度变慢怎么办 苹果手机微信打不开pdf怎么办 苹果手机打不开pdf怎么办 pdf文件超过了怎么办 pdf电脑删不了怎么办 联想笔记本摄像头横屏调竖屏怎么办 pdf文件打开失败怎么办 pdf复制文字乱码怎么办 电子发票乱码了怎么办 超星尔雅挂了怎么办 电脑应用双击打不开怎么办 电脑控制面板打不开怎么办 转换器无法打开文件怎么办 电脑文件无法打开怎么办 手机上jpg打不开怎么办 脸上全是黄褐斑怎么办 容易发胖的体质怎么办 感冒后一直咳嗽怎么办 感冒咳嗽怎么办小窍门 到了减肥平台期怎么办 减肥遇见平台期怎么办 脚冻伤了痒怎么办 冬天脚后跟冻了怎么办 夏天脚冻了怎么办 导航软件删了怎么办 婆婆爱打孩子怎么办 乙肝婆婆带孩子怎么办 婆婆不会教孩子怎么办