项目结构如下:
在src
目录下有个config.properties
文件,src目录
下的文件最终会被打包进WEB-INF/classes/
目录下。在web
目录下有个config
目录,该目录下也有个config.properties
文件。这些文件与目录最终在tomcat中的结构如下:
webapps
Servlet
config
config.properties
WEB-INF
classes
x.y.servlet
config.properties
web.xml
index.jsp
方式一
InputStream is=new FileInputStream("src/config.properties");
通过该种方式访问不到,因为这里的路径是相对路径,FileInputStream
的相对路径是根据jre
来确定的,因为这里是web
项目,jre
最后会交给tomcat
来管理,所以这里相对的路径是tomcat
的bin
目录。如果想访问到,需要在bin
目录下新建src
目录,并把config.properties
拷入。
方式二
ServletContext context=getServletContext();
InputStream is=new FileInputStream(context.getRealPath("config/config.properties"));
getRealPath
方法获取的是绝对路径,context.getRealPath("")
获取的路径是tomcat安装目录/webapps/Servlet/
。context.getRealPath("config/config.properties")
获取的路径是tomcat安装目录/webapps/Servlet/config/properties
。通过这种方式可以访问到。
方式三
ServletContext context=getServletContext();
InputStream is=context.getResourceAsStream("config/config.properties");
ServletContext
的getResourceAsStream
方法相对的目录是tomcat安装目录/webapps/Servet/
,通过这种方式可以访问到。
方式四
InputStream is=this.getClass().getClassLoader().getResourceAsStream("../../config/config.properties");
通过getClassLoader
方法获得类加载器,再调用类加载器的getResourceAsStream
方法。类加载器的getResourceAsStream
方法相对的目录是tomcat安装目录/webapps/Servet/WEB-INF/classes/
目录。所以需要使用../../
回到上上层目录才能访问到。