2014-01-28 40 views
0

我试图从backupData.properties中读取一些道具。它位于WEB-INF/classes/。我是这样做的:带属性文件的FileNotFoundException

public class Configures { 

    private static final String INPUT_FILE = "WEB-INF//classes//backupData.properties"; 


    public static String getMail() { 
     Properties prop = new Properties(); 
     try { 
      //load a properties file 
      prop.load(new FileInputStream(INPUT_FILE)); 

      //get the property value 
      return prop.getProperty("mail"); 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
     return null; 
    } 
} 

INPUT_FILE应该包含什么?我试图把它放在src,如src//backupData.properties,但它会引发FileNotFoundException。我GOOGLE了那个文件应该在CLASSPATH(根据我的理解,在WEB-INF/classes)。哪里不对?

PS。我正在使用Spring。

+0

你用绝对路径检查吗? – Kick

回答

2

这和Spring没有关系。如果您正在部署Web应用程序,则WEB-INF/classes中的所有内容都将从类路径的根目录开始显示。

您可以

InputStream in = Configures.class.getResourceAsStream("/backupData.properties"); 
prop.load(in); 

得到它InputStream该资源由于Web应用程序并不总是从它的.war文件中提取的,实际的属性文件可能只存在一个ZIP条目。因此,您不能(也不应该)使用FileInputStream来检索它。

Here's the javadoc.

+0

我不认为你想要名称中的斜杠。 – jalynn2

+0

@ jalynn2你为什么不这么认为? –

+0

,因为它在类路径的根目录中? – jalynn2

1

由于您使用的春天,我建议你 “可以” 用这个作为bean定义的一部分:

<property name="template" value="classpath:/backupData.properties"> 

Resource template = ctx.getResource("classpath:/backupData.properties"); 

或普通的老的建议用@Sotirios Delimanolis