在Java工程中,如果需要使用.properties类型的文件存放某些配置信息时,一般都是将.properties文件放在src目录下,代码一般都是这样写的:
Properties prop = new Properties();
InputStream is =
CommonUtils.class.getClassLoader().getResourceAsStream("config.properties");//假设当前这个方法是在CommonUtils类下面
prop.load(is);
在系统启动之后,config.properties中的key-value信息都可以获取,但是你想改变一下config.properties中的相关配置,但是又不能重启应用,你就会发现,明明已经修改了config.properties文件内容,为什么读出来的信息还是原先的呢?
原来使用
CommonUtils.class.getClassLoader().getResourceAsStream(“config.properties”)
这种加载方法会将config.properties文件加载到内存中,在下次需要读取时直接从内存中获取文件内的配置信息,而不是重新读取配置!
Properties prop = new Properties();
String path = CommonUtils.class.getClassLoader().getResource("config.properties").getPath();
InputStream is = new FileInputStream(path);
prop.load(is);
或者
Properties prop = new Properties();
String dirPath = Thread.currentThread().getContextClassLoader().getResource("config.properties").getPath();
FileInputStream file = new FileInputStream(dirPath);
prop.load(file);
prop.getProperty(key);//获取某个key的值