无线&移动互联网技术研发

换位思考·····
posts - 19, comments - 53, trackbacks - 0, articles - 283
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

java properties 文件的加载

Posted on 2009-06-07 01:02 Gavin.lee 阅读(1297) 评论(0)  编辑  收藏 所属分类: java SE & EE

我们在项目中肯定会碰到很多配置文件情况,在这种情况下,加载属性文件就是不可避免的了。
我这里提供两个方案:
【一】直接在src目录下或在其子包下:

package com.Gavin.tools.des;

import java.util.ResourceBundle;
/**
 * @descripte load resource
 * 
@author Gavin.lee
 * @date 2009-5-19上午09:49:32
 * 
@version 1.0
 *
 
*/

public class ResourceLoader {
    
private ResourceBundle resBundle;
    
    
public ResourceLoader(String resourceName) {
        resBundle 
= ResourceBundle.getBundle(resourceName);
    }

    
    
public String getString(String key) {
        
return resBundle.getString(key);
    }

    
    
public static void main(String args[]) {
        System.out.println(
new ResourceLoader("config").getString("username"));        //config in src
        System.out.println(new ResourceLoader("doingjava.config").getString("username"));    //config in doingjava
    }

}


使用 Properties类中的load方法


package com.yixun.wap;

/** *//**
 * 
@author Gavin.lee
 * @date 09-4-30 17:20pm
 * 
@version 1.0
 
*/

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class LoadProperties {
    
public void getSource(String source) {
        InputStream inputStream 
= this.getClass().getClassLoader().getResourceAsStream(source);
        Properties prop 
= new Properties();
        
try {
            prop.load(inputStream);
        }
 catch (IOException e) {
            e.printStackTrace();
        }
        
        prop.setProperty(
"truename""李显武");
        System.out.println(
"username:" + prop.getProperty("username"+ ",password:" + prop.getProperty("password"));
        System.out.println(
"truename:" + prop.getProperty("truename"));        
        prop.clear();    
//只想加载用一次的话 可以清空
        
//        System.out.println("truename:" + prop.getProperty("truename"));
//        System.out.println("username:" + prop.getProperty("username") + ",password:" + prop.getProperty("password"));
        
    }


    
public static void main(String[] args) {

        
new LoadProperties()..getSource("config.properties").getProperty("username");
    }


}



【二】可以指定properties 到自己想要的目录下:


package com.Gavin.tools.util;

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

/** *//**
 * 
 * @descripte 任意加载properties文件
 * 
@author Gavin.lee
 * @date 2009-6-7 0:55:18
 * 
@version 1.0
 
*/

public class ReadConfig {
    
static String path = WriteLog.class.getResource("/").getPath();
    
static String projectPath = path.substring(0, path.length()-16);// 到 WebRoot 下
    private static final String PFILE = projectPath + "config.properties";
        
    
/** *//**  
     * 对应于属性文件的文件对象变量  
     
*/

    
private File m_file = null;

    
/** *//**  
     * 属性文件的最后修改日期  
     
*/

    
private long m_lastModifiedTime = 0;

    
/** *//**  
     * 属性文件所对应的属性对象变量  
     
*/

    
private Properties m_props = null;

    
    
private static ReadConfig m_instance = new ReadConfig();

    
/** *//**  
     * 私有的构造器,用以保证外界无法直接实例化  
     
*/

    
private ReadConfig() {
        m_file 
= new File(PFILE);
        m_lastModifiedTime 
= m_file.lastModified();
        
if (m_lastModifiedTime == 0{
            System.err.println(PFILE 
+ " file does not exist!");
        }

        m_props 
= new Properties();
        
try {
            m_props.load(
new FileInputStream(PFILE));
        }
 catch (Exception e) {
            e.printStackTrace();
        }

    }


    
/** *//**  
     * 静态工厂方法  
     * 
@return 返还ReadConfig 类的单一实例  
     
*/

    
synchronized public static ReadConfig getInstance() {
        
return m_instance;
    }


    
/** *//**  
     * 读取一特定的属性项  
     *  
     * 
@param name 属性项的项名
     * 
@param defaultVal 属性项的默认值  
     * 
@return 属性项的值(如此项存在), 默认值(如此项不存在)  
     
*/

    
public String getConfigItem(String name, String defaultVal) {
        
long newTime = m_file.lastModified();
        
// 检查属性文件是否被其他程序
        
// 如果是,重新读取此文件

        
if (newTime == 0{
            
// 属性文件不存在   
            if (m_lastModifiedTime == 0{
                System.err.println(PFILE 
+ " file does not exist!");
            }
 else {
                System.err.println(PFILE 
+ " file was deleted!!");
            }

            
return defaultVal;
        }
 else if (newTime > m_lastModifiedTime) {
            
// Get rid of the old properties   
            m_props.clear();
            
try {
                m_props.load(
new FileInputStream(PFILE));
            }
 catch (Exception e) {
                e.printStackTrace();
            }

        }

        m_lastModifiedTime 
= newTime;
        String val 
= m_props.getProperty(name);
        
if (val == null{
            
return defaultVal;
        }
 else {
            
return val;
        }

    }


    
/** *//**  
     * 读取一特定的属性项  
     *  
     * 
@param name 属性项的项名  
     * 
@return 属性项的值(如此项存在), 空(如此项不存在)  
     
*/

    
public String getConfigItem(String name) {
        
return getConfigItem(name, "");
    }

    
    
public static void main (String args[]) {
        System.out.println(ReadConfig.getInstance().getConfigItem(
"username"));
    }

}


properties :
#url=wap.500wan.com
username = doingjava
password = lixianwu
birthday =1986-06-03

像这样的properties文件,用上面的三个类都是任意可读的。都在项目中试验过,均可使用。 O(∩_∩)O~
              ,%%%%%%%%,
           ,%%/\%%%%/\%%
          ,%%%\c "" J/%%%
 %.       %%%%/ o  o \%%%
 `%%.     %%%%    _  |%%%
  `%%     `%%%%(__Y__)%%'
  //       ;%%%%`\-/%%%'
 ((       /  `%%%%%%%'
  \\    .'          |
   \\  /       \  | |
    \\/         ) | |
     \         /_ | |__
     (___________)))))))【这个狮子很形象哈,呵呵】

 


只有注册用户登录后才能发表评论。


网站导航: