Search code examples
javaspringfile-iowarear

How to open a resource file in a WAR using a string pathname?


I am building a WAR/EAR and one of my components reads in many custom configuration files using File IO:

Reader reader = new BufferedReader(new FileReader(path));

The path above is a String that is passed as a property to this class through Spring's applicationContext.xml file.

What String path do I specify if I want to put all these configuration files inside a WAR? Can this even be done? Or is the component incorrect and should be using getResourceAsStream() instead?

I browsed around and found a lot of info on getResource() and URI. However, I could not find whether it is possible to create the right file path to a resource inside applicationContext.xml


Solution

  • In spring environment it's better to use spring resources API Simple example:

    @Inject
    private ResourceLoader resourceLoader;
    
    public void someMethod() {
        Resource resource = resourceLoader.getResource("file:my-file.xml");
        InputStream is = null;
        try {
            is = resource.getInputStream();
            // do work
            ....
        } finally {
            IOUtils.closeQuetly(is);
        }
    }
    

    If you want to access external files (non-classpath resources, which should be located in META-INF/resources within the archive) with non fixed paths you should put such paths in main properties file and load it on app deploy.

    edit: change @Resource to @Inject in example