PropertiesUtils

  • Post author:
  • Post category:其他


1.url:http://blog.csdn.net/majian_1987/article/details/11144335

2.jar:它来自commons-configuration-1.6.jar。

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
 
public class PropertiesUtils {
    private static String filePah = "";
    private final static String fileName = "jdbc.properties";
     
    static{
        filePah = PropertiesUtils.class.getClassLoader().getResource("").getPath();
        filePah += fileName;
    }
     
    public static boolean setProperty(final String key,final String value){
        return setProperty(fileName,key,value);
    }
     
    public static boolean setProperty(final String fileName,final String key,final String value){
        try {
            PropertiesConfiguration  config = null;
            if(StringUtils.isNotBlank(fileName)&&isValidExtension(fileName)){
                config = new PropertiesConfiguration(fileName);
                config.setProperty(key, value);
                config.save();
            }
            return true;
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        return false;
    }
     
     
    public static String getProperty(final String key){
        return getProperty(fileName,key);
    }
     
    public static String getProperty(final String fileName,final String key){
        String value = "";
         
        PropertiesConfiguration  config = null;
        try {
            if(StringUtils.isNotBlank(fileName)&&isValidExtension(fileName)){
                config = new PropertiesConfiguration(fileName);
                value = config.getString(key);
            }
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        return value;
    }
     
    private static boolean isValidExtension(final String fileName){
        String extension = FilenameUtils.getExtension(fileName);
        if(StringUtils.equalsIgnoreCase(extension, "properties")){
            return true;
        }else{
            return false;
        }
    }
     
    public static void main(final String[] args){
        System.out.println(PropertiesUtils.getProperty("key"));
    }
}

3.PropertiesUtils.java



版权声明:本文为weixin_43244841原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。