问题:如何读取web工程下的资源文件?
在ServletDemo01这个web工程下面的src目录下面有一个config.properties属性文件,那么如何才能读取到这个配置文件呢?
*采用流的形式:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Properties prop = new Properties();
InputStream is = new FileInputStream("src/config.properties");
prop.load(is);
System.out.println(prop.getProperty("name"));
}
这种读取的方式是有问题的,如果想要获取web工程下面的资源,用普通的FileInputStream的写法是没有用的,
因为路径不对了,这里是相对路径,其实是根据jre来确定的,但是这是一个web工程,jre后面会有tomcat管理,
所以这里真正的相对路径是是tomct里面的bi目录.
并且将工程放在tomcat里面之后,就没有了src了,可以看tomcat下面工程的目录结构;
解决办法就是在tomcat的bin目录下,建对应的文件夹,然后将属性文件放在这个目录下面,之后就可以采用流的形式来读取web工程下面的资源文件了.
使用tomcat提供的getServletContext()方法获取ServletContext对象
ServletContext context = getServletContext();
System.out.println(context.getRealPath("")); // 里面传的是空字符串
这个打印的结果是项目发布到tomcat的项目跟路径名字:
D:\software\tomcat\tomcats\apache-tomcat-web\webapps\ServletDemo01
有了这个项目在tomcat的根路径就可以获取这个项目下面的任意的资源文件了:
将资源文件放在WebRoot下面,那么在tomcat下的目录结构如下:(直接在项目的根目录下面)
*第一种方法获取web工程的资源文件
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = getServletContext();
Properties prop = new Properties();
// 通过绝对路径来读取文件
InputStream is = new FileInputStream(context.getRealPath("config/config.properties"));
// 通过流将文件读取到prop中
prop.load(is);
System.out.println(prop.getProperty("name"));
}
第二种方法获取web工程的资源文件
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// test01();
test02();
}
/**
*
* @throws IOException
*/
private void test02() throws IOException {
ServletContext context = getServletContext();
Properties prop = new Properties();
// 获取web工程下的资源转换成流对象,前面隐藏了当前工程的根目录
// 获取的是src下面的资源文件
// InputStream is = context.getResourceAsStream("WEB-INF/classes/config.properties");
// 获取的是WebRoot下面的资源文件
InputStream is = context.getResourceAsStream("config/config.properties");
prop.load(is);
is.close();
System.out.println(prop.getProperty("name"));
}
*第三种方法获取web工程下面的资源文件
使用ClassLoader
private void test03() throws IOException {
Properties prop = new Properties();
// 读取src下面的属性文件
// InputStream is = this.getClass().getClassLoader().getResourceAsStream("config.properties");
// 读取WebRoot下面的属性文件
InputStream is = this.getClass().getClassLoader().getResourceAsStream("../../config/config.properties");
prop.load(is);
System.out.println(prop.getProperty("name"));
}
对比分析:
使用ServletContext获取资源文件的相对路径相对的是ServletContext的根路径:
D:\software\tomcat\tomcats\apache-tomcat-web\webapps\ServletDemo01
但是使用ClassLoader获取资源文件的相对路径相对的是ClassLoader的根路径:
D:\software\tomcat\tomcats\apache-tomcat-web\webapps\ServletDemo01\WEB-INF\classes
这两个应该区分.