首页 > 代码库 > Java读取.properties文件
Java读取.properties文件
Java读取.properties配置文件时,可以使用apache的类库,需要用到如下的jar包:
假如存在这样的两个配置文件:
db.properties
include = db.propertiesusername = Jason Lipassword = 824
user.properties
url = http://192.168.1.1port = 8080
Java便可以这样读取:
ReadPropertiesFiles.java
package com.jason.test;import org.apache.commons.configuration.ConfigurationException;import org.apache.commons.configuration.PropertiesConfiguration;import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;/** * @ClassName: ReadPropertiesFiles * @Description: TODO(读取.properties配置文件) * @author Jason.XW.Li@pccw.com * @date 2014-8-19 下午2:48:25 * */public class ReadPropertiesFiles { public static void main(String[] args) { readFile(); } public static void readFile(){ String fileName = "user.properties"; PropertiesConfiguration config = null; String url = ""; String port = ""; String username = ""; String password = ""; try { config = new PropertiesConfiguration(fileName); config.setReloadingStrategy(new FileChangedReloadingStrategy());//自动刷新配置文件 url = config.getString("url"); port = config.getString("port"); username = config.getString("username"); password = config.getString("password"); config.setProperty("userno", "80546690");//该新加的键值对会保存在内存中 config.setAutoSave(true);//自动保存 System.out.println(url +":" + port + "&username = " + username +"&password = " + password + "&userno = " + config.getString("userno")); } catch (ConfigurationException e) { e.printStackTrace(); } }}
输出结果为:
http://192.168.1.1:8080&username = Jason Li&password = 824&userno = 80546690
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。