码迷,mamicode.com
首页 > 编程语言 > 详细

Java读取.properties文件

时间:2014-08-19 18:39:55      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   java   使用   os   

  Java读取.properties配置文件时,可以使用apache的类库,需要用到如下的jar包:

  bubuko.com,布布扣

  假如存在这样的两个配置文件:

  db.properties

include = db.properties
username = Jason Li
password = 824

  user.properties

url = http://192.168.1.1
port = 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

 

Java读取.properties文件,布布扣,bubuko.com

Java读取.properties文件

标签:des   style   blog   http   color   java   使用   os   

原文地址:http://www.cnblogs.com/Jason-coding/p/3922625.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!