java实现properties文件读写

来源:互联网 发布:jquery.format.js 编辑:程序博客网 时间:2024/05/21 06:58

点击查看原文:原文地址

package com.stj.core.common;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.util.Properties;public class PropertiesUtil {private File file = null;public PropertiesUtil(String filePath) { //构造时获取到项目的物理根目录 if(filePath != null && filePath.length() > 0){ try { file = new File(filePath); } catch (Exception e) {  e.printStackTrace();} } }  /** * 获取值 * @param key * @return */public String getProperties(String key){ InputStream fis = null; try { Properties prop = new Properties(); fis = new FileInputStream(getAbsolutePath()); prop.load(fis); return prop.getProperty(key); } catch (Exception e) { e.printStackTrace();}finally{ try{if(fis != null){fis.close();}}catch(Exception e){} } return ""; } /** * 赋值 * @param key * @param value * @throws Exception */public void setProperties(String key,String value)throws Exception{ Properties prop = new Properties();   FileOutputStream outputFile = null; InputStream fis = null; try { //输入流和输出流要分开处理, 放一起会造成写入时覆盖以前的属性 fis = new FileInputStream(getAbsolutePath()); //先载入已经有的属性文件 prop.load(fis); //追加新的属性 prop.setProperty(key, value); //写入属性 outputFile = new FileOutputStream(getAbsolutePath()); prop.store(outputFile, ""); outputFile.flush(); } catch (Exception e) { e.printStackTrace();throw e; }finally{ try{if(fis != null){fis.close();}}catch(Exception e){} try{if(outputFile != null){outputFile.close();}}catch(Exception e){} } }  public String getAbsolutePath(){ try { return file.getAbsolutePath(); } catch (Exception e) { e.printStackTrace();} return ""; } public static void main(String[] args) {PropertiesUtil pu = new PropertiesUtil("D:\\20170719test\\test.properties");System.out.println(pu.getProperties("isHead"));try {pu.setProperties("localId", "MKAH");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

原创粉丝点击