Java操作属性文件,支持新增或更新多个属性

来源:互联网 发布:雷神 知乎 编辑:程序博客网 时间:2024/05/16 10:58

Java操作属性文件,支持新增或更新多个属性

一、更新或新增单个属性的方法

/**    * 写入properties信息    * @param filePath  绝对路径(包括文件名和后缀名)    * @param parameterName  名称    * @param parameterValue 值    */   public static void writeProperties(String filePath, String parameterName, String parameterValue) {          Properties props = new Properties();       try {                   //如果文件不存在,创建一个新的           File file=new File(filePath);           if(!file.exists()){           file.createNewFile();       }            InputStream fis = new FileInputStream(filePath);           // 从输入流中读取属性列表(键和元素对)           props.load(fis);           fis.close();           OutputStream fos = new FileOutputStream(filePath);           props.setProperty(parameterName, parameterValue);           // 以适合使用 load 方法加载到 Properties 表中的格式,           // 将此 Properties 表中的属性列表(键和元素对)写入输出流           props.store(fos, parameterName);           fos.close(); // 关闭流       } catch (IOException e) {       System.err.println("Visit "+filePath+" for updating "+parameterName+" value error");       }   }


二、更新或新增N个属性的方法

/**    * @Title: writeMultiProperty    * @Description: TODO(修改属性文件的多个属性)    * @param filePath 属性文件路径(绝对路径)    * @param list 要更新或新增的一列值    * @return void      */   public static void writeMultiProperty(String filePath, List<Pobj> list){   if(list == null || list.size() == 0) return;      Properties props = new Properties();       try {           //如果文件不存在,创建一个新的           File file=new File(filePath);           if(!file.exists()){           file.createNewFile();       }           InputStream fis = new FileInputStream(filePath);           // 从输入流中读取属性列表(键和元素对)           props.load(fis);           fis.close();           OutputStream fos = new FileOutputStream(filePath);                      // 设置属性           for(Pobj obj : list){               props.setProperty(obj.getKey(), obj.getValue());           }                      // 保存至属性文件           props.store(fos, "update properties");                      fos.close(); // 关闭流       } catch (IOException e) {       System.err.println("Visit "+filePath+" for updating THE PROPERTIES value error");       }   }

多个属性的更新或新增需要用到一个辅助类,临时存储需要进行操作的值

/**     * @ClassName: Pobj     * @Description: TODO(辅助类,用来传递属性文件的每一条属性)     * @author Bruce oiiopro@live.cn     * @date 2014-11-18 下午11:31:00     */    public static class Pobj{        private String key;    private String value;        public Pobj(){}        /**     * <p>Title: </p>     * <p>Description: </p>     * @param key     * @param value     */    public Pobj(String key, String value){    this.key = key;    this.value = value;    }    public String getKey() {return key;}public void setKey(String key) {this.key = key;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}        }


三、读取属性文件的方法

import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import org.apache.commons.io.IOUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class SettingsJNWJ {private static final Logger LOGGER = LoggerFactory.getLogger(SettingsJNWJ.class);private static SettingsJNWJ instance;public Properties settings = new Properties();public SettingsJNWJ() {String filename = ("d:/jnwj.properties");LOGGER.info("Loading " + filename  + "...");InputStream stream = null;try {stream = new FileInputStream(filename);settings.load(stream);LOGGER.info( filename  + " loaded");} catch (IOException e) {LOGGER.error("Failed to  " + filename  , e);} finally {if(stream != null) IOUtils.closeQuietly(stream);}}public synchronized static SettingsJNWJ getInstance() {if (instance == null) {instance = new SettingsJNWJ();}return instance;}public String getString(String key) {return settings.getProperty(key);}public static void main(String[] args) {SettingsJNWJ s = SettingsJNWJ.getInstance();System.out.println(s.settings.toString());//System.out.println(SettingsJNWJ.getInstance().getString("uname"));}}

附,属性文件内容 [ jnwj.properties ]

uname=wckjupass=wckj123456unitcode=2340958039458

四、测试

/** * @Title: main * @Description: TODO(这里用一句话描述这个方法的作用) * @param @param args    设定文件 * @return void    返回类型 * @throws */    public static void main(String[] args) {        // TODO Auto-generated method stub//    test1();    test2();    }        /**     * @Title: 多个属性新增或更改的测试     */    public static void test2(){    List<Pobj> list = new ArrayList<Pobj>();    list.add(new Pobj("uname", "wckj"));    list.add(new Pobj("upass", "wckj123456"));    list.add(new Pobj("unitcode", "2340958039458"));    writeMultiProperty("D:/aiterw/conf/jnwj.properties", list);        System.out.println(SettingsJNWJ.getInstance().settings.toString());    }        /**     * @Title: 单个属性新增或更改的测试     */    public static void test1(){        //写文件        String passwork = "wckj123456";        String jnwj = Settings.getInstance().getString("jnwj"); //这里可以直接写成自己的属性文件位置, 如:d:/jnwj.properties        writeProperties(jnwj, "upass", passwork);          //从文件中取出userPassword,        System.out.println(SettingsJNWJ.getInstance().getString("upass"));    }


参考:http://www.oschina.net/code/snippet_116183_12472#21008




0 0
原创粉丝点击