关于java和 jsp读取 properties

来源:互联网 发布:电玩巴士淘宝3ds 编辑:程序博客网 时间:2024/04/29 11:57

package com.strongit.mail;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class Test {
 
 @SuppressWarnings({ "unchecked", "unchecked", "unchecked" })
 public static void main(String args[]) throws IOException {
    Properties prop = new Properties();
     String filePath = "info.properties";
//   
////   
    /**
     * 新增逻辑:
     * 1.必须先读取文件原有内容
     * 2.增加新的记录以后,再一起保存
     */
    //1.先读取文件原有内容
    InputStream in =Sendemail.class.getResourceAsStream(filePath);

  //此处如果用这个方法jsp读取文件,但属性增加或者修改后,如果没有重启服务器,读取的文件内容并没有被改变

 

 //如果文件修改后,要求显示页面有及时变换用下面的方法

 

 //    URL url =Sendemail.class.getResource(filePath);
//     File file =null;
//     try {
//    file = new File(url.toURI());
//     } catch (URISyntaxException e) {
//   e.printStackTrace();
//     }
//    InputStream in = new FileInputStream(file);

 

 

 

    prop.load(in);
    Map<String, Object> toSaveMap = new HashMap();
    Set keys = prop.keySet();
    for(Iterator itr = keys.iterator(); itr.hasNext();){
     String key = (String) itr.next();
     Object value = prop.get(key);
     System.out.println(value);
     toSaveMap.put(key, value);
    }
//    //2.增加你需要增加的属性内容
//    //toSaveMap.put("MailServerHost", "mail.126.com");
    // toSaveMap.put("sender_email", "killkill@126.com");
     // toSaveMap.put("receiver_email1", "b@126.com");
//    prop.putAll(toSaveMap);
//    prop.store(out, "==== after add ====");
   
    /**
     * 修改逻辑:重新设置对应Key的值即可,非常简单
     */
    prop.clear();
    //toSaveMap.put("MailServerHost", "mail.126.com");
   // toSaveMap.put("sender_email", "c@nanhai.gov.cn");
   // toSaveMap.put("receiver_email1", "b@126.com");
     toSaveMap.put("receiver_email2", "a@126.com");
   // toSaveMap.put("name", "killkill");
    //toSaveMap.put("password", "12345678");
    prop.putAll(toSaveMap);
    URL url =Sendemail.class.getResource(filePath);
    File file =null;
    try {
    file = new File(url.toURI());
  } catch (URISyntaxException e) {
   e.printStackTrace();
  }
    OutputStream out = new FileOutputStream(file);
    prop.store(out, "==== after modify ====");
   
    /**
//     * 删除逻辑:找到对应的key,删除即可
//     */ 
//    prop.clear();
//    toSaveMap.remove("name");
//    prop.putAll(toSaveMap);
//    prop.store(out, "==== after remove ====");
//   
    /**
     * 查询逻辑:你是知道滴
     */
    prop.load(in);
    System.out.println("name: " + prop.get("name"));
    System.out.println("password: " + prop.get("password"));
   
   }

 

}

原创粉丝点击