Java Web 获取资源路径之绝对路径

这是我的项目结构:

这是我部署在tomcat服务器之后,右键项目选择“Browse deployment location...”看到的结构:

可以看到,在tomcat服务器下,应用程序的根目录就是原来项目WebRoot下面的内容。想要获取a.properties、b.properties、c.properties这三个文件的内容,使用getRealPath(String path)方法:

public class TestServlet extends HttpServlet {
    
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        test1();
        test2();
        test3();
    }

    private void test3() throws IOException, FileNotFoundException {
        // 得到c.properties
        String path = this.getServletContext().getRealPath("/WEB-INF/classes/com/test/getresources/c.properties");
        Properties prop = new Properties();
        prop.load(new FileInputStream(path));
        System.out.println(prop.getProperty("key"));
    }

    private void test2() throws IOException, FileNotFoundException {
        // 得到b.properties
        String path = this.getServletContext().getRealPath("/WEB-INF/classes/b.properties");
        Properties prop = new Properties();
        prop.load(new FileInputStream(path));
        System.out.println(prop.getProperty("key"));
    }

    private void test1() throws IOException, FileNotFoundException {
        // 得到a.properties
        String path = this.getServletContext().getRealPath("/WEB-INF/a.properties");
        Properties prop = new Properties();
        prop.load(new FileInputStream(path));
        System.out.println(prop.getProperty("key"));
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

 在浏览器访问TestServlet,控制台输入三个文件的内容:

注意:getRealPath() 方法根据资源名称的到资源的绝对路径,但是该方法对于不同的app server会返回不同的结果,同时,该方法会受到 war 和 non-war 的影响,对于一个打包应用来说,是没有RealPath概念的。

因此,推荐使用getResourceAsStream(Strig path)的方法:

private void test4() throws IOException {
        // 使用getResourceAsStream
        Properties prop = new Properties();
        prop.load(this.getServletContext().getResourceAsStream("/WEB-INF/a.properties"));
        System.out.println(prop.getProperty("key"));
    }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        test1();
        test2();
        test3();
        test4(); // 使用getResourceAsStream
    }

运行结果如下:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值