java操作properties文件

来源:互联网 发布:e盾网络验证破解方法 编辑:程序博客网 时间:2024/04/30 11:01
package comm.file;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.URI;import java.net.URISyntaxException;import java.net.URL;import java.util.Properties;/** * 该类为java操作.properties文件的工具类 *  * @author wxq *  */public class PropertyFileUtil {String propertyFileName = "test.properties";// 读取的文件是否为XML文件boolean isXMLFile = false;Properties prop = null;/** * 获取property文件 *  * @return * @throws URISyntaxException */private File getPropertyFile() throws URISyntaxException {File propFile = null;URL url = ClassLoader.getSystemResource(propertyFileName);propFile = new File(url.toURI());return propFile;}/** * 将properties文件中的信息读到Properties对象中 *  * @throws IOException */private void readPropertiesFromPropFile() throws IOException {InputStream in = null;in = PropertyFileUtil.class.getResourceAsStream("/" + propertyFileName);// in=PropertyFileUtil.class.getClassLoader().getSystemResourceAsStream("test.properties");prop = new Properties();if (isXMLFile) {prop.loadFromXML(in);} else {prop.load(in);}in.close();}/** * 读取指定key的value值 *  * @param key * @return * @throws IOException */public String getValueOfPropertyFile(String key) throws IOException {this.readPropertiesFromPropFile();return prop.getProperty(key);}/** * 向properties文件中增加key&value *  * @param key * @param value * @return * @throws Exception */public boolean addOrUpdatePropertyIntoPropFile(String key, String value)throws Exception {boolean isAddSuccess = false;File propFile = null;FileOutputStream fos = null;if (key != null && !key.equals("")) {propFile = getPropertyFile();this.readPropertiesFromPropFile();prop.setProperty(key, value);fos = new FileOutputStream(propFile);prop.store(fos, "add " + key + " " + value);fos.flush();fos.close();isAddSuccess = true;}return isAddSuccess;}/** * 从properties文件中删除一行 *  * @param key * @return * @throws URISyntaxException * @throws IOException */public boolean delPropertyFromPropFile(String key)throws URISyntaxException, IOException {boolean isAddSuccess = false;File propFile = null;FileOutputStream fos = null;if (key != null && !key.equals("")) {propFile = getPropertyFile();this.readPropertiesFromPropFile();prop.remove(key);fos = new FileOutputStream(propFile);prop.store(fos, "delete " + key);fos.flush();fos.close();isAddSuccess = true;}return isAddSuccess;}/* * XML文件示例 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE properties * SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> * <comment></comment> <entry key="a">1</entry> </properties> */}

原创粉丝点击