首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

tomcat 中 java 解析properties(实时变更)

2012-09-10 
tomcat 中 java 解析properties(实时变化)有个朋友要用getClass().getResourceAsStream() 提取test.proper

tomcat 中 java 解析properties(实时变化)
有个朋友要用getClass().getResourceAsStream() 提取test.properties

但是在服务器运行过程中 无论怎么更改test.properties

得出的数据还是最初的那个

我后来试了一下 代码如下
package test;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Test {
    Properties pp = null;

    public Properties getData() throws IOException {
        InputStream is = getClass().getResourceAsStream("/test.properties");
        // InputStream is = new FileInputStream(
        // "D:\\java\\apache-tomcat-5.5.17\\apache-tomcat-5.5.17\\webapps\\testp\\WEB-INF\\classes\\test.properties");
        System.out.println(is.hashCode());
        pp = new Properties();
        pp.load(is);
        System.out.println(pp.hashCode());
        // Properties pp = System.getProperties();
        // Enumeration<String> enu = (Enumeration<String>) pp.propertyNames();
        // while(enu.hasMoreElements()){
        // String name = enu.nextElement();
        // System.out.println(name + "=" +pp.getProperty(name));
        // }
        // is.close();
        is.close();
        return pp;
    }

    public static Properties getProperties() {
        try {
            return new Test().getData();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        while (true) {
            System.out.println(getProperties());
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
上面这个解析的Properties pp 的hashcode 始终不变

而InputStream 的hash 缺一直改变

由此可以推断结论有
getClass().getResourceAsStream() 是ClassLoader 加载Class一样的把test.properties 加载进了内存


但是针对上面的红字我写了MAIN函数做为测试

现在发现如果我更改Properties ,会立刻做出反应

main函数中的代码我的理解如下 每次ClassLoader都在加载ClassPath下的文件,当发现改变就构成Properties 改变

所以我想这是不是tomcat的ClassLoader 的一个bug ??

所以如果想test.properties随时变 用绝对路径 InputStream is = new FileInputStream("绝对路径")
就可以了

主要是因为把资源文件放在classpath下了,而改变了以后,资源文件没有重新编译,因此放入非classpath目录下就可以了

热点排行