FileNotFoundException with properties file

2019-09-10 08:10发布

I'm trying to read some props from backupData.properties. It locates in WEB-INF/classes/. This is how I do:

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;
    }
}

What INPUT_FILE should contain? I was trying to put it in src, like src//backupData.properties, but it throws FileNotFoundException. I googled that file should locate in CLASSPATH(in WEB-INF/classes as I understood). What is wrong?

PS. I'm using Spring.

2条回答
Deceive 欺骗
2楼-- · 2019-09-10 08:33

This has nothing to do with Spring. If you are deploying a web application, everything in WEB-INF/classes will appear starting at the root of the classpath.

You can get it the InputStream to that resource with

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

Since a web application is not always extracted from its .war file, the actual properties file might only exist as a zip entry. As such, you can't (and shouldn't) retrieve it with FileInputStream.

Here's the javadoc.

查看更多
时光不老,我们不散
3楼-- · 2019-09-10 08:37

Since you are using SPRING , I suggest you "CAN" use this as part of your Bean definition:

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

or

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

or the plain old as suggested by @Sotirios Delimanolis

查看更多
登录 后发表回答