java中的资源文件_Java中获取资源文件的方法总结

这里总结3中方法获取资源文件的

ServletContext

Class

ClassLoader

文件的位置

bde6f29fb43a7c276066dbb5bd436775.png

1. ServletContext

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

PrintWriter pw = response.getWriter();

ServletContext context = this.getServletContext();

/**

* 获取不同路径下的资源文件

* servletContext是相对于项目的根目录的,这里为WebContent

*/

InputStream inputA = context.getResourceAsStream("/a.txt");

InputStream inputB = context.getResourceAsStream("/WEB-INF/classes/cn/zydev/b.txt");

InputStream inputC = context.getResourceAsStream("/WEB-INF/classes/c.txt");

/**

* 获取真实的磁盘路径

*/

String realPath = context.getRealPath("/WEB-INF/classes/c.txt");

/**

* 获取指定目录下的文件(包括目录,深度为1级)

*/

Set rsc = context.getResourcePaths("/WEB-INF");

String a = IOUtils.toString(inputA);

String b = IOUtils.toString(inputB);

String c = IOUtils.toString(inputC);

pw.print(a+"
");

pw.print(b+"
");

pw.print(c+"
");

pw.print(realPath+"
");

pw.println(rsc);

}

结果显示:

d63f5f02c32e058186275ab893d1b5d3.png

2. ClassLoader

使用ClassLoader是相对于classes的

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

PrintWriter pw = response.getWriter();

/**

* ClassLoader是相对于classes参照的

* 第一个斜杠可以不写,也可以写成./(熟悉Linux的应该很清楚)

*/

ClassLoader cl = this.getClass().getClassLoader();

InputStream inputA = cl.getResourceAsStream("/../../a.txt");

InputStream inputB = cl.getResourceAsStream("/cn/zydev/b.txt");

InputStream inputC = cl.getResourceAsStream("/c.txt");

String a = IOUtils.toString(inputA);

String b = IOUtils.toString(inputB);

String c = IOUtils.toString(inputC);

pw.print(a+"
");

pw.print(b+"
");

pw.print(c+"
");

}

得到结果:

b14386fa58727d50e0ee9fe71cfe6453.png

3. class

路径前斜杠表示相对于当前的class,不加斜杠相对于classes

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

PrintWriter pw = response.getWriter();

Class cs = this.getClass();

//不加斜杠表示相对于class(CServlet)

InputStream inputA = cs.getResourceAsStream("../../../../a.txt");

InputStream inputB = cs.getResourceAsStream("b.txt");

//加斜杠,相对于classes

InputStream inputC = cs.getResourceAsStream("/c.txt");

String a = IOUtils.toString(inputA);

String b = IOUtils.toString(inputB);

String c = IOUtils.toString(inputC);

pw.print(a+"
");

pw.print(b+"
");

pw.print(c+"
");

}

得到结果:

ce3d8f62eef1e842a6add44ee32e4502.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值