首页

关于通过配置文件PropertieFileReader工具类实现配置文件读取及持久化存储刷新文件

标签:PropertieFileReader,配置文件保存更新,配置文件工具类,properties     发布时间:2018-03-27   

一、前言

通过下面配置文件PropertieFileReader读取操作类,实现对配置文件init.properties键值读取getString、键值替换关键字并保存刷新到文件restore等操作。

二、源码说明

import java.io.FileOutputStream;@b@import java.io.InputStream;@b@import java.io.OutputStream;@b@import java.util.Properties;@b@import java.util.Set;@b@@b@ @b@public class PropertieFileReader {@b@	@b@	private static Properties config = new Properties(); //单例@b@	@b@	private  static final String cfg_properties="init.properties";@b@@b@	// 类加载时通过类加载器读取类路径下的配置文件@b@	static {@b@		try{@b@			InputStream in = PropertieFileReader.class.getClassLoader()@b@							.getResourceAsStream(cfg_properties);// 通过类加载器获得类路径下该属性文件的一个输入流@b@			config.load(in);// 从输入流中读取属性列表@b@			in.close();@b@			@b@		} catch (Exception e) {@b@			e.printStackTrace();@b@		}@b@	}@b@	@b@	public static String getString(String key) {@b@		return config.getProperty(key);@b@	}@b@	@b@	public static String getString(String key, String defaultValue) {@b@		return config.getProperty(key, defaultValue);@b@	}@b@	@b@	public  static  void  restore(String key, String regex,String replacement)throws Exception {@b@		String targetVal=getString(key);@b@		targetVal=targetVal.replaceAll(regex, replacement);@b@		store(key,targetVal);@b@	}@b@	@b@	public  static  void  restoreAll(String regex,String replacement)throws Exception {@b@		Set<Object> keyobjs=config.keySet();@b@		String key=null;@b@		for(Object kobj:keyobjs){@b@			key=String.valueOf(kobj);@b@			restore(key,regex,replacement);@b@		}@b@	}@b@	@b@	public  static  boolean  IPRestoreAll(String replacement)throws Exception{@b@		String regexIP=getString("cluster_mapping");@b@		if(regexIP==null)return false;@b@		if(regexIP.contains("api.xwood.net->")){@b@			regexIP=regexIP.replaceAll("api.xwood.net->", "");@b@		}@b@		if(!regexIP.equals(replacement)){@b@			restoreAll(regexIP,replacement);@b@			System.out.println("_____ip has replaced______regexIP@"+regexIP+"_________@replace@"+replacement);@b@		}else{@b@			System.out.println("________________ip is still valid_________________replace nothing");@b@			return false;@b@		}@b@		@b@		return true;@b@		@b@	}@b@	@b@	public static void store(String key, String value) throws Exception {@b@		config.setProperty(key, value);@b@		OutputStream fos = new FileOutputStream(PropertieFileReader.class.getClassLoader().getResource(cfg_properties).getPath()); @b@		config.store(fos, "");@b@	}@b@@b@	public static Properties getInstance() {@b@		return config;@b@	}@b@	@b@	@b@	public  static  void  main(String[] args) throws Exception{@b@		PropertieFileReader.restore("copid", "00","aa");@b@	}@b@@b@}