java中操作properties文件

 private String loadSysPath(){
  String temp = "./cluster/siteId/conf/netMap.properties";
  if(temp.indexOf("siteId")!=-1){
   String siteId= ContextHolder.getContext().getSiteId();
   temp = temp.replaceAll("siteId", siteId);
  }  
  return temp;
 }
 
 /**
  * 修改邮箱上限值
  * @param key 邮箱关键字
  * @param value 邮箱上限值
  * @return
  */
 public void changePropertiesValue( @Read(key = "key") String key,@Read(key = "value") String value) {
  
       Properties p = new Properties();  
        FileInputStream in;  
        try {
         String propertiesPath = this.loadSysPath();
            in = new FileInputStream(propertiesPath);  
            p.load(in);
            in.close();
            p.setProperty(key,value);//设置属性值,如属性不存在新建
            FileOutputStream out=new FileOutputStream(propertiesPath);//输出流
            p.store(out,"netMap set");//设置属性头,如不想设置,请把后面一个用""替换掉
            out.flush();//清空缓存,写入磁盘
            out.close();//关闭输出流
        } catch (Exception e) {
            logger.error("changePropertiesValue failed in ManageIndexAction",e);
        }  
     
 }

 /**
  * 获取邮箱上限值
  * @param key 邮箱关键字 
  * @return 邮箱保存最大值,-1为读取数值失败
  */
 public String getNetMapPropertiesValue(String key) {
  String s = "";
  String type = "0";
        Properties p = new Properties();//加载属性文件读取类  
        FileInputStream in=null;
        OutputStreamWriter os=null;       
        String propertiesPath = this.loadSysPath();
        try { 
         
         File file= new File(propertiesPath);
         //判断文件是否存在,不存在创建并添加该邮箱的默认上限数量
         if(!file.exists()){
          String ss = propertiesPath.substring(0, propertiesPath.lastIndexOf("/"));
          File root= new File(ss);
          if (!root.exists())  {
        root.mkdirs();    
       }       
       os = new OutputStreamWriter(new FileOutputStream(file));   
                os.close();
               
                changePropertiesValue(key,"0");
         }
            //propertiesFileName如test.properties  
            in = new FileInputStream(propertiesPath);//以流的形式读入属性文件  
            p.load(in);//属性文件将该流加入的可被读取的属性中  
            in.close();//读完了关闭  
            s = p.getProperty(key);//取得对应的属性值 
            if(StringUtils.isBlank(s)){
              changePropertiesValue(key,"0");
              s = "0";
            }
            type = s;
        } catch (Exception e) {  
          logger.error(" getMaxNumByMsgBoxType error in PrivateMessageServiceImpl ",e);
        }finally{
         try{
          if(in!= null){
           in.close();           
          }if(os != null){
           os.close();
          }
         }catch(Exception ex){
           logger.error(ex);
         }
        }       
        return type;
 }

你可能感兴趣的:(java,OS)