我已经创建了一个java maven web应用程序。现在我的问题是,我必须使用资源包或properties类来访问属性文件。但是这个属性文件在webapp/resources文件夹中,即与我的js和css文件在同一个目录中。
我有这个实用方法,但如果需要,我可以编写新的方法:
public static ResourceBundle getBundle(String baseName, String absolutePath) {
File file = new File(absolutePath);
ResourceBundle bundle = null;
try {
URL[] urls = { file.toURI().toURL() };
ClassLoader loader = Thread.currentThread().getContextClassLoader();
bundle = ResourceBundle.getBundle(baseName, Locale.getDefault(), loader);
} catch (MalformedURLException e) {
}
return bundle;
}我的项目结构:
-project
-------src
--------main
---------java
---------resources
---------webapp
----------resources
-----------app.properties
-----------script.js发布于 2013-03-28 17:21:40
您的属性文件似乎是相对于web应用程序根目录的。在这种情况下,您可以使用getResource() in ServletContext
发布于 2013-03-28 17:22:31
您可以向自己发出HttpUrlConnection (mydomain/myapp/resources/app.properties),但我要说这是一个丑陋的解决方案
更常见的方法是将主资源重新定位到类路径中(例如:src/ app.properties /app.properties)。如果你使用Spring,你就可以使用ClasspathResource。或者你可以阅读这篇文章:How to really read text file from classpath in Java
请记住,将app.properties放在那里可能意味着您的所有用户都能够读取app.properties
发布于 2013-03-29 16:53:54
我最终通过将我的webapp/resources文件夹添加到类路径来让它正常工作。在将它添加到类路径之后,我们可以简单地这样做-
ResourceBundle bundle = ResourceBundle.getBundle(bundleName);https://stackoverflow.com/questions/15677943
复制相似问题