简体   繁体   中英

How to load external file using ClassPathResource in Spring?

We have one file on one drive (C:\\megzs\\realm.properties). We would like to load this file and read the content using the ClassPathResource available in Spring. But we see the file is not found exception. The code we are trying is

Resource resource = new ClassPathResource("file:c:/megzs/realm.properties");
Properties prop = PropertiesLoaderUtils.loadProperties(resource);

Here we are using ClassPathResource to load external file. Can ClassPathResource load the external file ?
And How can we load mutiple properties files (one from classpath and another from absolute path) ??

if you want to access file based resource use FileSystemResource and provide it to PropertiesLoaderUtils.loadProperties() method. Below code reads property file from file system if not exists, it will load it from the classpath. hope it helps.

    public static Properties getProperties(String propertyFile) {
    try {
        Resource resource = new FileSystemResource(propertyFile);
        if (!resource.exists()) {
            resource = new ClassPathResource(propertyFile);
        }
        return PropertiesLoaderUtils.loadProperties(resource);
    } catch (Exception ignored) {
        return null;
    }
}

im loading many properties using @PropertySource() and properties will be read using Environment object may be you should try with this approach you approach is not wrong bt it is somewhat confusing to me

@Configuration
    @PropertySource({
        "classpath:config.properties",
        "file:/path/to/application.properties" //if same key, this will 'win'
    })
    public class AppConfig {

        @Autowired
        Environment env;

                public void ReadProperties() {

        String property1 = env.getProperty("property");
        String property2 = env.getProperty("property2");
                }

                //if theres same key found in the second property 
                //file key in the second property file wiil be read
    }

In the below snippet , screen-shots is a folder under src/test/resources and the Test class is under src/test/java

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

Resource fileResource = new ClassPathResource(
                "screen-shots/HomePage-attachment.png");

assertNotNull(fileResource);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM