在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

在Java和Web中读取properties文件

2016-12-13 12:56| 发布者: zhangjf| 查看: 509| 评论: 0

摘要: 普通java工程读取properties文件 web工程中servlet读取properties文件 web工程中非servlet读取properties文件 不论哪种情况加载properties文件的大概流程是一样的,只不过是生成流时使用的文件路径有区别. ...
普通java工程读取properties文件 web工程中servlet读取properties文件 web工程中非servlet读取properties文件

不论哪种情况加载properties文件的大概流程是一样的,只不过是生成流时使用的文件路径有区别.

假设db.properties文件:username=root

如果知道properties文件的绝对路径:

  1. String path = "C:\db.properties";
  2. FileInputStream in = new FileInputStream(path);
  3. Properties prop = new Properties();
  4. prop.load(in);
  5. prop.getProperty("username");
复制代码

web工程中,文件在工程中的位置$app/WEB-INF/classes/db.properties

在Servlet中有2种方式:

  1. InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
  2. Properties prop = new Properties();
  3. prop.load(in);
  4. prop.getProperty("username");
复制代码
  1. String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
  2. FileInputStream in = new FileInputStream(path);
  3. Properties prop = new Properties();
  4. prop.load(in);
  5. prop.getProperty("username");
复制代码

非Servlet时,假设类名为Demo,要使用类装载器来读取,也有两种方式:
1.直接将文件装载到内存中
2.得到文件的绝对路径再进行操作

  1. InputStream in = Demo.class.getClassLoader().getResourceAsStream("db.properties");
  2. Properties prop = new Properties();
  3. prop.load(in);
  4. prop.getProperty("username");
  5. //弊端:类装载器加载内容时,会先查找内存中是否已经存在相应的内容
  6. //如果有就不再加载直接使用内存中的,所以此方法,第一次加载后,如果文件内容有变动,第二次加载后还是原来的内容,无法加载修改后的内容
  7. //下边的方法取文件的绝对路径来加载不会有这种问题
复制代码
  1. String path = Demo.class.getClassLoader().getResource("db.properties").getPath();
  2. FileInputStream in = new FileInputStream(path);
  3. Properties prop = new Properties();
  4. prop.load(in);
  5. prop.getProperty("username");
复制代码

上面在使用FileInputStream时传入的都是绝对路径,也可以使用相对路径:

普通java工程:是相对于当前类的所在路径
web工作:是相对于$tomcat/bin ($tomcat为tomcat的路径名)

来自:http://my.oschina.net/lhplj/blog/386014

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-7 12:08

Copyright 2015-2025 djqfx

返回顶部