Servlet中通过ServletContext获取工程根目录下文件

Servlet中通过ServletContext获取工程根目录下文件_第1张图片

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;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ServletDemo2 extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 获得到ServletContext对象
        ServletContext servletContext = config.getServletContext();
        // 获得WEB-INF下的文件的绝对路径
        // getRealPath的参数内容不会被校验,只有真正要用这个路径的时候才知道路径对不对
        // String path = servletContext.getRealPath("test.properties");
        // 获得项目的根目录
        String path = servletContext.getRealPath("/");
        System.out.println(path);
        // 获取文件夹的路径
        String upload = servletContext.getRealPath("/upload");
        System.out.println(upload);
        // 获取资源流
        InputStream asStream = servletContext.getResourceAsStream("/WEB-INF/test.roperties");
        Properties properties = new Properties();
        try {
            properties.load(asStream);
            System.out.println(properties.get("key"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
}
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;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ServletDemo3 extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 获得到ServletContext对象
        ServletContext context = config.getServletContext();
        /*第一种方法:获得classpash下的资源的文件的流,用于classpath下的文件发布之后是在/WEB-INF/classes/下
           所以去指定的"/WEB-INF/classes/test1.properties"
        */
        InputStream stream = context.getResourceAsStream("/WEB-INF/classes/test1.properties");

        // 第二种方法
        /*
        * 使用类加载器的方式来读取classpath下的资源文件,
        * 好处不依赖与servletContext,任何类都可以获得classpath下的资源文件,不需要再自己指定/WEB-INF/classes/
        * */
        InputStream stream1 = this.getClass().getClassLoader().getResourceAsStream("test1.properties");
        Properties properties = new Properties();
        try {
            properties.load(stream1);
            System.out.println(properties.get("key"));
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
}

 

你可能感兴趣的:(java)