2010-07-01 94 views
24

属性文件位置是WEB-INF/classes/auth.properties如何读取Web应用程序中的属性文件?

我无法使用特定于JSF的方式(使用ExternalContext),因为我需要一个不依赖于Web模块的服务模块中的属性文件。

我已经尝试过

MyService.class.getClassLoader().getResourceAsStream("/WEB-INF/classes/auth.properties"); 

但它返回null

我也试着用FileInputStream来读它,但它需要完整的路径是不可接受的。

任何想法?

回答

49

几个注意事项:

  1. 你应该更喜欢通过ClassLoaderThread#getContextClassLoader()返回。

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
    

    这将返回访问所有资源parentmost类加载器。 Class#getClassLoader()将只返回有问题的类的(子)类加载器,它本身可能不能访问所需的资源。它将始终在具有单个类加载器的环境中工作,但并不总是在具有类似webapps的类加载器的复杂层次结构的环境中。

  2. /WEB-INF文件夹不在类路径的根目录中。 /WEB-INF/classes文件夹是。所以你需要加载相关的属性文件。

    classLoader.getResourceAsStream("/auth.properties"); 
    

    如果您选择使用Thread#getContextClassLoader(),删除前导/

它采用ServletContext#getResourceAsStream()“抽油烟机下”只能从web内容返回资源(那里的/WEB-INF文件夹坐着)的具体JSF-ExternalContext#getResourceAsStream(),而不是从classpath。

+0

不在这种情况下 – unbeli 2010-07-01 18:48:31

+0

@unbeli:你是什么意思? – Roman 2010-07-01 18:51:15

+1

@unbeli:当你将它作为JAR发布时,祝你好运:) – BalusC 2010-07-01 18:51:31

8

试试这个:

MyService.class.getClassLoader().getResourceAsStream("/auth.properties"); 

读取文件与getResourceAsStream看起来在类路径中寻找资源加载。由于classes目录位于您的Web应用程序的类路径中,因此应将该文件称为/auth.properties

5

ResourceBundle(http://download.oracle.com/javase/6/docs/api/java/util/ResourceBundle.html)通过属性文件的相对/绝对路径解决了大部分问题。

它使用Resource类并将其指向虚拟类以引用属性文件。

例如:

  1. 你有一个文件调用MAINProperties.properties和里面有一个属性: mail.host = foo.example。com
  2. 创建一个名为MAINProperties的哑类,没有任何内容。
  3. 使用下面的代码:

    ResourceBundle.getBundle( “com.example.com.MAINProperties”)的getProperty( “mail.host”)

,就是这样。没有InputStreams必需。

P.D. Apache Commons有一个名为Apache Commons Configuration的库,它具有很多功能(可重新加载的文件,多种域类型),可以与上述结合使用。

相关问题