现在的位置: 首页 > 综合 > 正文

web项目中读取properties文件的方法总结

2017年12月11日 ⁄ 综合 ⁄ 共 2300字 ⁄ 字号 评论关闭
项目结构:
方式一:
  1. /**
  2. * 传统方式
  3. */
  4. private void test1() throws FileNotFoundException, IOException {
  5. // FileInputStream in = new FileInputStream("src/test.properties"); // 错误写法1 java项目中这么写是正确的
  6. // FileInputStream in = new FileInputStream("classes/test.properties");//错误写法2
  7. FileInputStream in = new FileInputStream("test.properties");//把test.properties文件copy到tomcate的bin目录下
  8. Properties prop = new Properties();
  9. prop.load(in);
  10. String driver = prop.getProperty("driver");
  11. String url = prop.getProperty("url");
  12. System.out.println("driver-==-="+driver);
  13. System.out.println("url-==-="+url);
  14. }
解析:
   错误写法1:要是java项目,这么写是正确的,可以读到配置文件,但是web项目就会报找不到路径的错误,因为web项目会把test.properties文件编译到WEB-INF目录下的classes文件夹下。
   错误写法2:这么看似没问题了,但是会报跟1一样的错误,因为这是相对路径,谁调用此类就是相对于谁,故这是相对于java虚拟机,本项目时用tomcate启动的java虚拟机,故回去tomcate的bin目录下去找classes/test.properties文件,找不到故报错
方式二:
  1. private void test2() throws IOException {
  2. System.out.println("test2");
  3. InputStream in = this.getServletContext().getResourceAsStream("WEB-INF/classes/test.properties");
  4. Properties prop = new Properties();
  5. prop.load(in);
  6. String driver = prop.getProperty("driver");
  7. String url = prop.getProperty("url");
  8. System.out.println("driver-==-="+driver);
  9. System.out.println("url-==-="+url);
  10. }
方式三:
  1. private void test3() throws FileNotFoundException, IOException {
  2. String path = this.getServletContext().getRealPath("WEB-INF/classes/test.properties");//拿到资源在硬盘上的路径
  3. FileInputStream in = new FileInputStream(path);
  4. System.out.println("test3");
  5. Properties prop = new Properties();
  6. prop.load(in);
  7. String driver = prop.getProperty("driver");
  8. String url = prop.getProperty("url");
  9. System.out.println("driver-==-="+driver);
  10. System.out.println("url-==-="+url);
  11. }
方式四:
  1. private void test4() throws IOException {
  2. /**
  3. * 读取webroot目录下的配置文件
  4. */
  5. System.out.println("test4");
  6. InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/test11.properties");
  7. Properties prop = new Properties();
  8. prop.load(in);
  9. String driver = prop.getProperty("driver");
  10. String url = prop.getProperty("url");
  11. System.out.println("driver-==-="+driver);
  12. System.out.println("url-==-="+url);
  13. }
方式五:
  1. private void test5() throws IOException {
  2. /**
  3. * 类装载器方式读取,我常用的方式
  4. */
  5. InputStream in = readProp.class.getClassLoader().getResourceAsStream("test.properties");
  6. System.out.println("类装载器方式");
  7. Properties prop = new Properties();
  8. prop.load(in);
  9. String driver = prop.getProperty("driver");
  10. String url = prop.getProperty("url");
  11. System.out.println("driver-==-="+driver);
  12. System.out.println("url-==-="+url);
  13. }

抱歉!评论已关闭.