通过ServletContext获得工程根目录路径、读取文件以及获得classpath目录下的文件

HttpServletDemo02.java:

package com.fl.servlet;


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class HttpServletDemo02 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }
    @Override
    public void init(ServletConfig config) throws ServletException {
        ServletContext sc = config.getServletContext();
        //不管根目录下是否有temp.txt,在这里不会检测。
        String path = sc.getRealPath("temp.txt");
        //不管根目录下有没有upload目录,这里也不会报错,而是会
        //直接输出根目录的完整目录后,再在后面加上upload。
        String path1 = sc.getRealPath("/upload");
        //因此一般getRealPath用于获取根目录路径。
        String path2 = sc.getRealPath("/");
        System.out.println(path);
        System.out.println(path1);
        System.out.println(path2);
        //这里通过完整路径,把文件放入流中。
        InputStream in = sc.getResourceAsStream("/WEB-INF/temp.txt");
        Properties prop = new Properties();
        
        try {
            prop.load(in);
            System.out.println(prop.get("key"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>HttpServletDemo02</servlet-name>
    <servlet-class>com.fl.servlet.HttpServletDemo02</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>HttpServletDemo02</servlet-name>
    <url-pattern>/servlet/HttpServletDemo02</url-pattern>
  </servlet-mapping>
</web-app>

temp.txt:

    key=dddd;

 

输出结果:

获得classpath目录下的文件:

下面有两种方法:

扫描二维码关注公众号,回复: 5805887 查看本文章

InputStream in = sc.getResourceAsStream("/WEB-INF/classes/temp.txt");//这种方式不太好
InputStream in = this.getClass().getClassLoader().getResourceAsStream("temp.txt");//类加载方式,不依赖ServletCntext,任何类都可以获得classpath下的文件。

猜你喜欢

转载自www.cnblogs.com/cq0143/p/10668331.html
今日推荐