项目运行过程中修改.properties文件问题

来源:互联网 发布:中国高铁发展知乎 编辑:程序博客网 时间:2024/05/17 01:22

项目运行过程中需要修改配置文件的代码。菜鸟贴出记录自己成长。。

/**

showOu 要修改为的值   
*/

public void setAttribute(String value) {
        OutputStream out = null;
        InputStream in = null;
        if(showOu == null){
            showOu = "ou";
        }
        try {
            //获取服务器上配置文件所在位置
            File file = new File(com.avicit.tools.GetSystemPath.getClassesPath() + "show.properties");  
            if (!file.exists())  
                file.createNewFile();
            
            in = new FileInputStream(file);
           
            
            Properties p = new Properties();
            p.load(in);
            in.close();
            p.setProperty("Attr_name", value);

         //out的位置很重要。一定要在setProperties之后。不然会把原来的所有其他属性覆盖掉

           out = new FileOutputStream(file);

          //将修改后的文件存回去

            p.store(out, null);
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            try {
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


注意每次修改后的配置文件在本地是不会变的,因为路径获取的是服务器上的路径,修改的也为服务器上的配置文件。

如果在项目运行过程中修改了配置文件,则再次读取配置文件之前要重新从服务器上读取一次,因为会有配置文件的缓存,不再次读取的话还是修改以前的值。
0 0
原创粉丝点击