java讀取,更改配置文件工具

 

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

public class ReadConf {
      private static Logger logger = Logger.getLogger(ReadConf.class);
      
      private static Properties properties = null;
      private static  String filepath="X:/config.properties";
      static {
      try {
          properties = new Properties();
          InputStream is = new FileInputStream(filepath);
          BufferedReader bf = new BufferedReader(new  InputStreamReader(is));
          properties.load(bf);
       } catch (Exception e) {
          logger.warn(e.getMessage());
      }
      }
      

       //讀取classpath下的配置文件
        private static String getString1(String key){
            ResourceBundle resource = ResourceBundle.getBundle("config");
            return resource.getString(key);
        }
      

       //讀取任意位置的配置文件
        public static String getString(String key){
            
             return properties.getProperty(key);
        }
      //更改配置文件
        public static void setString(String key , String value) {
                     
             OutputStream out;
            try {
                out = new FileOutputStream(filepath);
            
             properties.put(key, value);
             properties.store(out,  " Update '" + key + "' value");
            } catch (FileNotFoundException e) {
                      e.printStackTrace();
            } catch (IOException e) {
                      e.printStackTrace();
            }
        }

}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章