有個朋友要用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 ??
以上言論,均屬我的猜測,還望高手指點.
新發現:
InputStream is = Test.class.getClassLoader().getResourceAsStream(// .getResourceAsStream(
InputStream is = Test.class.getResourceAsStream(// .getResourceAsStream(
這樣加載的Properties 是兩個不同的實例 我的意思是想說兩份不同的內存
所以如果想test.properties隨時變 用絕對路徑 InputStream is = new FileInputStream("絕對路徑")
就可以了