java操作properties文件


package com.ccdevote.www.common.PropertiesDeal;
 
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
 
/**
 * Properties 类存在于包 Java.util 中,该类继承自 Hashtable ,它提供了几个主要的方法: 1. load
 * (nputStream inStream) ,从输入流中读取属性列表(键和元素对)。 2. getProperty(String key),
 * 用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value 。 3. setProperty ( String
 * key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
 * 通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty (
 * String key)
 * 
 * 来搜索。 4. store(OutputStream out,String comments) ,以适合使用 load 方法加载到 Properties
 * 表中的格式,将此 Properties 表中的属性列
 * 
 * 表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。 5. clear() ,清除所有装载的 键 -
 * 值对。该方法在基类中提供。 有了以上几个方法我们就可以对 .properties 文件进行操作了! 总结:
 * java的properties文件需要放到classpath下面,这样程序才能读取到, 有关classpath实际上就是java类或者库的存放路径:
 * 在java工程中,properties放到class文件一块; 在web应用中,最简单的方法是放到web应用的WEB-INF\classes 目录下即可,
 * 也可以放在其他文件夹下面,这时候需要在设置classpath环境变量的时候,将这个文件夹路径加到classpath变量中,这样也也可以读取到
 * 
 * 。 在此,你需要对classpath有个深刻理解,classpath绝非系统中刻意设定的那个系统环境变量,WEB-INF\classes其实也是,
 * java工程的
 * 
 * class文件目录也是。
 */
 
public class PropertiesTools {
    /*
     * 读取properties的全部信息
     */
     
 
    public static void readProperties(String fileNamePath) throws IOException {
        Properties props = new Properties();
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(fileNamePath));
            // 如果将in改为下面的方法,必须要将.Properties文件和此class类文件放在同一个包中
            // in = propertiesTools.class.getResourceAsStream(fileNamePath);
            props.load(in);
            Enumeration en = props.propertyNames();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String Property = props.getProperty(key);
                System.out.println(key + "=" + Property);
            }
        } catch (Exception e) {
            if (null != in)
                in.close();
            e.printStackTrace();
        } finally {
            if (null != in)
                in.close();
        }
    }
 
    /*
     * 根据key读取value
     */
    public static String getValue(String fileNamePath, String key)
            throws IOException {
        Properties props = new Properties();
        InputStream in = null;
        try {
            in = new FileInputStream(fileNamePath);
            // 如果将in改为下面的方法,必须要将.Properties文件和此class类文件放在同一个包中
            // in = propertiesTools.class.getResourceAsStream(fileNamePath);
            props.load(in);
            String value = props.getProperty(key);
            // 有乱码时要进行重新编码
            // new String(props.getProperty("name").getBytes("ISO-8859-1"),
            // "GBK");
            return value;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (null != in)
                in.close();
        }
 
    }
 
    /*
     * 写入properties信息
     */
    public static void setProperties(String fileNamePath, String parameterName,
            String parameterValue) throws IOException {
        Properties prop = new Properties();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(fileNamePath);
            // 如果将in改为下面的方法,必须要将.Properties文件和此class类文件放在同一个包中
            // in = propertiesTools.class.getResourceAsStream(fileNamePath);
            prop.load(in);
            out = new FileOutputStream(fileNamePath);
            prop.setProperty(parameterName, parameterValue);
            prop.store(out, parameterName);// 保存
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != in)
                in.close();
            if (null != out)
                out.close();
        }
    }
 
    public static void main(String[] args) throws IOException {
        // 方法一:
        // String fileNamePath = "info.properties";
        // 上面不变,用类中注释掉的in =
        // TestProperties.class.getResourceAsStream(fileNamePath);方法,必须要将.Properties文件和此
         
        // class类文件放在同一个包中
     
        // 方法二:
        String fileNamePath = "config//info.properties";
        // 这个方法需要在项目的要目录下建立config文件夹,然后把properties文件放在config下
 
        // 取值
        System.out.println("取username的值:" + getValue(fileNamePath, "username"));
        System.out.println("取age的值:" + getValue(fileNamePath, "age"));
        // 写值
        setProperties(fileNamePath, "age", "21");
        // 取此文件所有配置信息
        readProperties(fileNamePath);
    }
 
}
================================================================================================================================
ackage com.common.util;
 
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
 
import org.apache.log4j.Logger;
 
/**
 * 对.properties属性文件相关操作的工具类,该类无法被继承。
 * @author Belin Wu
 * @version 1.0 2012-07-24
 */
public final class PropertiesHelper {
     
    @SuppressWarnings("unused")
    private static final Logger LOGGER = Logger.getLogger(PropertiesHelper.class);
     
    /**
     * PropertiesHelper类的私有构造方法
     */
    private PropertiesHelper() {
    }
     
    /**
     * 根据给定的资源文件的路径值,加载单个资源文件,返回Properties类对象的引用。若有异常产生,则Properties类对象的引用为null。
     * @param filePath 资源文件的路径值
     * @return 给定资源文件所对应的Properties类对象的引用。
     */
    public static Properties loadPropertiesFile(String filePath) {
        Properties properties = new Properties();
        InputStream is = null;
         
        try {
            try {
                is = new FileInputStream(filePath);
                properties.load(is);
            } finally {
                if (is != null) {
                    is.close();
                    is = null;
                }
            }
        } catch (Exception e) {
            properties = null;
        }
         
        return properties;
    }
     
    /**
     * 根据多个资源文件的路径值,加载多个资源文件。
     * @param filePaths 多个资源文件的路径值
     * @return 存放Properties类型引用的散列表,该散列表以资源文件的路径值为键。
     * @see PropertiesHelper#loadPropertiesFile(String)
     */
    public static Map<String, Properties> loadPropertiesFiles(List<String> filePaths) {
        Map<String, Properties> propertiesMap = new HashMap<String, Properties>();
         
        for (String filePath : filePaths) {
            propertiesMap.put(filePath, loadPropertiesFile(filePath));
        }
         
        return propertiesMap;
    }
     
    /**
     * 根据给定的文件路径值,存放properties引用相关的资源文件到磁盘上。
     * @param filePath 目标资源文件的路径值
     * @param properties Properties类型的引用
     * @return 操作成功,返回true;否则,返回false。
     * @see PropertiesHelper#storePropertiesFile(String, Map)
     */
    public static boolean storePropertiesFile(String filePath, Properties properties) {
        return storePropertiesFile(filePath, getProperty(properties));
    }
     
    /**
     * 根据给定的文件路径值和欲存放的键值对,将目标资源文件存放到磁盘上。
     * @param filePath 目标资源文件的路径值
     * @param propertyMap 所有键值对
     * @return 操作成功,返回true;否则,返回false。
     */
    public static boolean storePropertiesFile(String filePath, Map<String, String> propertyMap) {
        Properties properties = new Properties();
        FileWriter writer = null;
         
        try {
            try {
                writer = new FileWriter(filePath);
                 
                for (Map.Entry<String, String> entry : propertyMap.entrySet()) {
                    properties.put(entry.getKey(), entry.getValue());
                }
                 
                properties.store(writer, null);
            } finally {
                if (writer != null) {
                    writer.close();
                    writer = null;
                }
            }
             
            return true;
        } catch(Exception e) {
            return false;
        }
    }
     
    /**
     * 处理多个资源文件存放到磁盘上。
     * @param filePaths 多个资源文件的路径值集合
     * @param propertyMaps 多个资源文件中的键值对集合
     * @return 操作成功,返回true;否则,返回false。
     * @see PropertiesHelper#storePropertiesFile(String, Map)
     */
    public static boolean storePropertiesFiles(List<String> filePaths, List<Map<String, String>> propertyMaps) {
        int filePathSize = filePaths.size();
         
        if (filePathSize != propertyMaps.size()) {
            return false;
        }
         
        for (int i = 0; i < filePathSize; i++) {
            if (!storePropertiesFile(filePaths.get(i), propertyMaps.get(i))) {
                return false;
            }
        }
         
        return true;
    }
     
    /**
     * 获得给定键所关联的值的字符串形式。若键不存在,则返回给定的默认值。若properties为null,则返回null。
     * @param key 键
     * @param defaultValue 默认值
     * @param properties 目标资源文件所对应的Properties类对象的引用
     * @return 给定键所关联的值的字符串形式
     */
    public static String getString(String key, String defaultValue, Properties properties) {
        return (properties == null) ? null : properties.getProperty(key, defaultValue);
    }
     
    /**
     * 获得给定键所关联的值的字符串形式。若键不存在,则返回给定的默认值。若properties为null,则返回null。
     * @param key 键
     * @param defaultValue 默认值
     * @param properties 目标资源文件所对应的Properties类对象的引用
     * @return 给定键所关联的值的字符串形式
     */
    public static Integer getInteger(String key, Integer defaultValue, Properties properties) {
        String stringValue = (properties == null) ? null : properties.getProperty(key, defaultValue.toString());
        Integer value = null;
         
        if (stringValue == null) {
            return null;
        }
         
        try {
            value = Integer.valueOf(stringValue);
        } catch (NumberFormatException e) {
            value = defaultValue;
        }
         
        return value;
    }
     
    /**
     * 获得给定键所关联的值的布尔形式。若键不存在,则返回给定的默认值。若键所对应的值不为true,则返回的是false。若properties为null,则返回null。
     * @param key 键
     * @param defaultValue 默认值
     * @param properties 目标资源文件所对应的Properties类对象的引用
     * @return 给定键所关联的值的布尔形式
     */
    public static Boolean getBoolean(String key, Boolean defaultValue, Properties properties) {
        String stringValue = (properties == null) ? null : properties.getProperty(key, defaultValue.toString());
        return (stringValue == null) ? null : Boolean.valueOf(stringValue);
    }
     
    /**
     * 获得给定键所关联的值的浮点型形式。若键不存在,则返回给定的默认值。若properties为null,则返回null。
     * @param key 键
     * @param defaultValue 默认值
     * @param properties 目标资源文件所对应的Properties类对象的引用
     * @return 给定键所关联的值的浮点型形式
     */
    public static Double getDouble(String key, Double defaultValue, Properties properties) {
        String stringValue = (properties == null) ? null : properties.getProperty(key, defaultValue.toString());
        Double value = null;
         
        if (stringValue == null) {
            return null;
        }
         
        try {
            value = Double.valueOf(stringValue);
        } catch (NumberFormatException e) {
            value = defaultValue;
        }
         
        return value;
    }
     
    /**
     * 获得给定键所关联的值的日期形式。若键不存在,则返回给定的默认值。若properties为null,则返回null。
     * @param key 键
     * @param defaultValue 默认值
     * @param properties 目标资源文件所对应的Properties类对象的引用
     * @return 给定键所关联的值的日期形式
     */
    public static Date getDate(String key, Date defaultValue, Properties properties) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String stringValue = (properties == null) ? null : properties.getProperty(key, sdf.format(defaultValue));
        Date value = null;
         
        if (stringValue == null) {
            return null;
        }
         
        try {
            value = sdf.parse(stringValue);
        } catch (ParseException e) {
            value = defaultValue;
        }
         
        return value;
    }
     
    /**
     * 根据给定的若干个键和Properties类型的引用,获得资源文件中若干个指定的键值对。
     * @param keys 若干个键
     * @param properties Properties类型引用
     * @return 若干个指定的键值对
     */
    public static Map<String, String> getProperty(List<String> keys, Properties properties) {
        Map<String, String> propertyMap = new HashMap<String, String>();
         
        for (String key : keys) {
            propertyMap.put(key, properties.getProperty(key));
        }
         
        return propertyMap;
    }
     
    /**
     * 根据给定的若干个键和资源文件的路径值,获得资源文件中若干个指定的键值对。该方法会调用getProperty(List, Properties)方法。
     * @param keys 若干个键
     * @param filePath 资源文件的路径值
     * @return 若干个指定的键值对
     * @see PropertiesHelper#getProperty(List, Properties)
     */
    public static Map<String, String> getProperty(List<String> keys, String filePath) {
        return getProperty(keys, loadPropertiesFile(filePath));
    }
     
    /**
     * 获得给定Properties类型引用所对应的资源文件中的所有键值对。
     * @param properties Properties类型的引用
     * @return 资源文件中的所有键值对
     */
    public static Map<String, String> getProperty(Properties properties) {
        Map<String, String> propertyMap = new HashMap<String, String>();
         
        for (Iterator<Object> iter = properties.keySet().iterator(); iter.hasNext();) {
            String key = iter.next().toString();
            propertyMap.put(key, properties.getProperty(key));
        }
         
        return propertyMap;
    }
     
    /**
     * 根据给定的资源文件的路径,获得资源文件中的所有键值对。该方法会调用getProperty(Properties)方法。
     * @param filePath 资源文件的路径值
     * @return 资源文件中的所有键值对
     * @see PropertiesHelper#getProperty(Properties)
     */
    public static Map<String, String> getProperty(String filePath) {
        return getProperty(loadPropertiesFile(filePath));
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值