访问不在构建路径上的java属性文件



我已经创建了一个java maven web应用程序。现在我的问题是,我必须使用资源束或属性类访问属性文件。但是这个属性文件在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

似乎你的属性文件是相对于web应用程序的根。在这种情况下,您可以在ServletContext

中使用getResource()

你可以发出一个HttpUrlConnection给你自己(mydomain/myapp/resources/app.properties),但我想说这是一个丑陋的解决方案

更常见的方法是将app.properties重新定位到类路径中(例如:src/main/resources)。然后如果你使用Spring,你可以使用ClasspathResource。或者你可以阅读这篇文章:如何真正从Java的类路径中读取文本文件

请记住,将app.properties放在那里可能意味着所有用户都能够读取app.properties

我终于得到了它的工作通过添加我的webapp/资源文件夹到classpath。将它添加到类路径后,我们可以简单地使用-

ResourceBundle bundle = ResourceBundle.getBundle(bundleName);

最新更新