如何从java中的web服务获取属性文件的上下文路径?
我正在尝试从我的应用程序读取属性文件的上下文路径,
properties.load(this.getClass().getResourceAsStream(path));
import java.util.Properties;
public class test1 {
public String getValues()
{
PropertiesFileReader fileReader = new PropertiesFileReader();
Properties prop = fileReader.getProp("/messages/AttachFile.properties");
String out = prop.getProperty("FILE_NAME");
return out;
}
}
当属性文件位于 WEB-INF -> 下时,这会起作用。类 ->消息->我的文件
但是当我将此文件移动到其他文件夹时,例如 WEB-INF ->消息-> myfile
它似乎没有获取路径...
编辑:我没有使用 servlet...
I am trying read the context path of a properties file from my application,
properties.load(this.getClass().getResourceAsStream(path));
import java.util.Properties;
public class test1 {
public String getValues()
{
PropertiesFileReader fileReader = new PropertiesFileReader();
Properties prop = fileReader.getProp("/messages/AttachFile.properties");
String out = prop.getProperty("FILE_NAME");
return out;
}
}
This works when the properties file is under WEB-INF -> classes -> messages -> myfile
but when i move this file to some other folder like WEB-INF -> messages -> myfile
it doesn't seem to get the path...
EDIT: I am not using servlets...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果失败,因为新路径不是类路径的一部分,而 Class#getResourceAsStream() 从类路径加载资源。
/WEB-INF/classes
默认情况下是 Servlet API 规范中指定的类路径的一部分,这就是它起作用的原因。我建议将其保留在类路径中或将新路径/WEB-INF/resources
添加到类路径中。如果您使用的是 Eclipse 这样的 IDE,那么您可以通过将其添加为项目构建路径中的源文件夹来完成此操作(这会在构建过程中将其移回
/WEB-INF/无论如何,类)。或者,您也可以在 Java 源根目录中创建一个
resources
包,然后将文件放在那里。它也将成为类路径的一部分。If fails because the new path is not part of the classpath while
Class#getResourceAsStream()
loads resources from the classpath. The/WEB-INF/classes
is by default part of the classpath as specified in the Servlet API specification, that's why it worked. I recommend to keep it in the classpath or to add the new path/WEB-INF/resources
to the classpath.If you're using an IDE like Eclipse, then you can do it by adding it as Source Folder in project's build path (which would during build move it back into the
/WEB-INF/classes
anyway). Alternatively, you can also just create aresources
package in the Java source root and then put the file there. It will become part of the classpath as well.您只需在前面添加
/WEB-INF/
:you just have to prepend
/WEB-INF/
:当您说您不使用 servlet 时,您的意思是什么?这段代码如何运行?
基本上,当您使用 servlet 时,类路径上只有 WEB-INF/classes 和 WEB-INF/lib 。因此您无法使用类加载器访问资源。但您可以使用 ServletContext 访问它们。因此,假设您的代码在 Servlet/JSP 中运行,您可以执行以下操作:
When you say that you are not using servlets, what do you mean? How this code runs?
Basically, when you do use servlets, only WEB-INF/classes and WEB-INF/lib are on the classpath. So you cannot access the resources using classloaders. BUT you can access them using the ServletContext. So assuming your code runs in Servlet/JSP, you can do the following: