从 Grails 中的 java 类中读取属性文件
Read properties file from java class in Grails
我将 urls.properties 放在 conf 文件夹和 src/java 文件夹中,但是当我想从 grails 项目中的 java 类中读取此文件时,出现错误:java.io.FileNotFoundException: urls.properties (The system cannot find the file specified).
我尝试使用以下代码读取此文件:
|
1
2 3 |
io = new FileInputStream("urls.properties");
prop.load(io); url = prop.getProperty(urlName); |
出了什么问题,为什么会出现这个错误?我在 Config.groovy 中有一个 conf 参数 as
|
1
|
grails.config.locations = ["classpath:urls.properties"]
|
有关加载外部配置文件的信息,请参阅手册中的这一章:
http://grails.org/doc/2.3.7/guide/single.html#configExternalized
在使用 grails.config.locations 指定属性文件后,这些属性会在您的应用程序启动时自动加载,因此它们应该已经可以在 grailsApplication.config 对象中访问,如下所示:
|
1
2 3 |
def grailsApplication // Injects the grailsApplication object to your service/controller
... grailsApplication.config.myproperty |
在此处阅读有关如何访问配置属性的更多信息:
http://grails.org/doc/2.3.7/guide/conf.html
您尝试对代码执行的操作是从当前工作目录加载一个文件,而该文件可能不存在于那里。因此错误代码。
编辑
如果你想加载一个存在于类路径中的文件,你应该把它作为资源加载。像这样:
|
1
|
InputStream is = MyClass.class.getResourceAsStream("urls.properties");
|
...其中 MyClass 是与 urls.properties 位于同一包中的类。不要忘记检查流是否为空,因为如果它无法加载资源。
相关讨论
- 但是我如何从 Java 类而不是 Groovy 类中读取这些参数?
- 啊,这就是问题所在。如果您想让它变得复杂,请参阅此博客文章:burtbeckwith.com/blog/?p=1017
- 请参阅我对如何从 java 中的资源加载文件的编辑。这可能是一个更快的解决方案。