您的位置:首页 > 运维架构

使用Properties去读取配置文件,并获得具体内容值

2014-12-21 10:12 721 查看
有时候,写了一个配置文件,需要知道读出来的内容对不对,我们需要测试一下,看看读出来的跟我们要的是不是一样。这里写了一个工具类,用来读取配置文件里面的内容。

一、使用Properties工具类来读取。

1.新建一个java工程,导入需要的jar包,新建一个配置文件 如下图:



2.配置文件的内容:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/csdn
user=root
pwd=123456
initsize=1
maxactive=1
maxwait=5000
maxidle=1
minidle=1


3.读取配置文件工具类:

package com.cnblogs.daliu_it;

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

/**
* 读取配置文件
* @author daliu_it
*/
public class GetProperties {
public static void getProperties() {
try {
// java.util.Properties
/*
* Properties类用于读取properties文件 使用该类可以以类似Map的形式读取配置 文件中的内容
*
* properties文件中的内容格式类似: user=openlab 那么等号左面就是key,等号右面就是value
*/
Properties prop = new Properties();

/*
* 使用Properties去读取配置文件
*/
FileInputStream fis = new FileInputStream("config.properties");
/*
* 当通过Properties读取文件后,那么 这个流依然保持打开状态,我们应当自行 关闭。
*/
prop.load(fis);
fis.close();
System.out.println("成功加载完毕配置文件");

/*
* 当加载完毕后,就可以根据文本文件中 等号左面的内容(key)来获取等号右面的 内容(value)了
* 可以变相的把Properties看做是一个Map
*/
String driver = prop.getProperty("driver").trim();
String url = prop.getProperty("url").trim();
String user = prop.getProperty("user").trim();
String pwd = prop.getProperty("pwd").trim();
System.out.println("driver:" + driver);
System.out.println("url:" + url);
System.out.println("user:" + user);
System.out.println("pwd:" + pwd);

} catch (Exception e) {
e.printStackTrace();
}
}
}


4.测试类:

package com.daliu_it.test;

import java.sql.SQLException;

import org.junit.Test;

import com.cnblogs.daliu_it.GetProperties;

public class testCase {

/**
* 获得配置文件
* @throws SQLException
*/
@Test
public void testgetProperties() throws SQLException {
GetProperties poperties=new GetProperties();
poperties.getProperties();
}
}


5.效果图:



二、使用ResourceBundle类来读取。

package com.souvc.redis;

import java.util.Locale;
import java.util.ResourceBundle;

/**
* 类名: TestResourceBundle </br>
* 包名: com.souvc.redis
* 描述: 国际化资源绑定测试 </br>
* 开发人员:souvc </br>
* 创建时间: 2015-12-10 </br>
* 发布版本:V1.0 </br>
*/
public class TestResourceBundle {
public static void main(String[] args) {

ResourceBundle resb = ResourceBundle.getBundle("config",Locale.getDefault());
String driver=resb.getString("driver");
String url=resb.getString("url");
String user=resb.getString("user");
String pwd=resb.getString("pwd");
String initsize=resb.getString("initsize");
System.out.println(driver);
System.out.println(url);
System.out.println(user);
System.out.println(pwd);
System.out.println(initsize);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐