如何从WAR的classes目录中读取文件? [英] How can I read file from classes directory in my WAR?

查看:129
本文介绍了如何从WAR的classes目录中读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从Java WAR应用程序的类路径中读取文本文件.如何将其读取为InputStream.文件位于/WEB-INF/classes/文件夹中,但是当我使用以下代码时,它仅返回null.

I need to read text file from the classpath in Java WAR application. How can I read it as InputStream. File is located in /WEB-INF/classes/ folder, but when I use following code, it just returns null.

InputStream input = servletContext.getClass().getClassLoader().getResourceAsStream("my_filename.txt");

推荐答案

使用正斜杠将其前缀以表示类路径的根:

Prefix it with a forward slash to denote the root of the classpath:

getResourceAsStream("/my_filename.txt")

或者,您可以使用serlvetContext.getResourceAsStream(..)查找相对于上下文根的资源.所以类将是/WEB-INF/classes.

Alternatively, you can use the serlvetContext.getResourceAsStream(..) which looks for resources relative to the context root. So classes would be /WEB-INF/classes.

这篇关于如何从WAR的classes目录中读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆