Java读取properties配置文件

Java读取properties配置文件

新建需要读取的配置文件,jdbc.properties,文件内容如下:

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost/diagnosis?useUnicode=true&characterEncoding=utf8

jdbc.username=root

jdbc.password=root

一、java读取项目内的properties配置文件

可以增加将配置文件jdbc.properties放到项目工程的根目录下,通过调用下面的代码读取:

String propertyFileName = “jdbc”; //不需要加载properties后缀

ResourceBundle resourceBundle = ResourceBundle.getBundle(propertyFileName);

String result = resourceBundle.getString(key);

 

二、java读取外部的properties配置文件

         配置文件是没有打包到应用工程jar包中,是独立出来的;可以通过获取配置文件的路径在读取:

         1、在项目的根目录下新建一个config文件夹,将配置文件放入到该文件夹。

         2、打包jar包是,不要将该目录打包。

         3、在jar的目录下,新建config文件夹,将配置文件放入到该文件夹。

 

         4、调用配置文件的代码:

final Properties properties = new Properties();

final String filePath = System.getProperty("user.dir") + "/config/jdbc.properties";

InputStream in = new BufferedInputStream(new FileInputStream(filePath));

properties.load(in);

 

String result = properties.getProperty(key);

 

 

posted @ 2012-10-17 14:52  thisAndroid  阅读(852)  评论(0编辑  收藏  举报