java 如何从我的 WAR 中的 classes 目录读取文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3888226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:51:42  来源:igfitidea点击:

How can I read file from classes directory in my WAR?

javafileclasspathwar

提问by newbie

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.

我需要从 Java WAR 应用程序的类路径中读取文本文件。我怎么能把它读作 InputStream。文件位于 /WEB-INF/classes/ 文件夹中,但是当我使用以下代码时,它只返回 null。

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

回答by Bozho

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

用正斜杠作为前缀来表示类路径的根:

getResourceAsStream("/my_filename.txt")

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

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