动态读取配置文件 config

来源:互联网 发布:获取httppost请求数据 编辑:程序博客网 时间:2024/05/18 17:41

动态读取config配置文件,  否则配置文件修改之后不能读取更新部分报错,


 try {
InputStream in =new FileInputStream("ip.config");//这里配置文件地址写成全路径就会报错,应该只写文件名

   p.load(in);
   in.close();
   if(p.containsKey("fuck")){
       this.url = p.getProperty("fuck");
       c = this.url.split(",");
   }
} catch (IOException ex) {
ex.printStackTrace();
}
return c;



InputStream stream=Thread.currentThread().getClass().getResourceAsStream("/config.properties");
但不能这样写:
InputStream stream = Thread.currentThread().getClass().getClassLoader().getResourceAsStream("config.properties");
但可以这样写:
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("config.properties");
InputStream stream = new FileInputStream("/config.properties");  //相对于项目web-inf/classes目录
为什么 我就不再解释了吧。
如果是在web项目中,我们还可以这样写:
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties");
不过servlet已经帮我们封装了,我们一般这样写:
ServletContext.getRealPath("/")  这里的斜杠是相对与项目部署后的WebRoot为根目录。


va里加载Properties文件都是通过Java.util包里的Properties类的load()方法来加载一个Properties配置文件,load()方法需要接收一个文件输入流,而InputStream的构建需要Java.io.File对象,即new FileInputStream(new File(path));现在问题就集中在如何动态获取

ava里加载Properties文件都是通过Java.util包里的Properties类的load()方法来加载一个Properties配置文件,load()方法需要接收一个文件输入流,而InputStream的构建需要Java.io.File对象,即new FileInputStream(new File(path));现在问题就集中在如何动态获取这个路径。


0 0
原创粉丝点击