欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java项目读取properties路径问题

程序员文章站 2022-05-31 11:46:22
...
java项目读取properties路径问题

1.项目结构

java项目读取properties路径问题

2.方法一

/**
* 传统方式
*/
private void test1() throws FileNotFoundException, IOException {
		// FileInputStream in = new FileInputStream("src/main/resources/properties/url.properties"); // 错误写法1  java项目中这么写是正确的,web项目不行
		 //  FileInputStream in = new FileInputStream("classes/test.properties");//错误写法2
		     FileInputStream in = new FileInputStream("test.properties");//把test.properties文件copy到tomcate的bin目录下
		     Properties prop = new Properties();
		     prop.load(in);
		     String driver = prop.getProperty("driver");
		     String url = prop.getProperty("url");
		     System.out.println("driver-==-="+driver);
		     System.out.println("url-==-="+url);
	}

解析:
错误写法1:要是java项目,这么写是正确的,可以读到配置文件,但是web项目就会报找不到路径的错误,因为web项目会把test.properties文件编译到WEB-INF目录下的classes文件夹下。
错误写法2:这么看似没问题了,但是会报跟1一样的错误,因为这是相对路径,谁调用此类就是相对于谁,故这是相对于java虚拟机,本项目时用tomcate启动的java虚拟机,故回去tomcate的bin目录下去找classes/test.properties文件,找不到故报错


3.方法二

private void test2() throws IOException {
		System.out.println("test2");
		InputStream in = this.getServletContext().getResourceAsStream("WEB-INF/classes/test.properties");
		 Properties prop = new Properties();
		 prop.load(in);
		 String driver = prop.getProperty("driver");
		 String url = prop.getProperty("url");
		 System.out.println("driver-==-="+driver);
		 System.out.println("url-==-="+url);
	}


4.方法三

private void test3() throws FileNotFoundException, IOException {
		String path = this.getServletContext().getRealPath("WEB-INF/classes/test.properties");//拿到资源在硬盘上的路径
		FileInputStream in = new FileInputStream(path);
		 System.out.println("test3");
		 Properties prop = new Properties();
		 prop.load(in);
		 String driver = prop.getProperty("driver");
		 String url = prop.getProperty("url");
		 System.out.println("driver-==-="+driver);
		 System.out.println("url-==-="+url);
	}


5.方法四

private void test4() throws IOException {
		/**
		 * 读取webroot目录下的配置文件
		 */
		 System.out.println("test4");
		 InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/test11.properties");
		 Properties prop = new Properties();
		 prop.load(in);
		 String driver = prop.getProperty("driver");
		 String url = prop.getProperty("url");
		 System.out.println("driver-==-="+driver);
		 System.out.println("url-==-="+url);
	}


6.方法五

private void test5() throws IOException {
		/**
		 * 类装载器方式读取,我常用的方式
		 */
		InputStream in  = readProp.class.getClassLoader().getResourceAsStream("test.properties");
		System.out.println("类装载器方式");
		 Properties prop = new Properties();
		 prop.load(in);
		 String driver = prop.getProperty("driver");
		 String url = prop.getProperty("url");
		 System.out.println("driver-==-="+driver);
		 System.out.println("url-==-="+url);
	}


转载于:https://my.oschina.net/gaoguofan/blog/753386