How to get resources directory path programmatically

JavaSpringIo

Java Problem Overview


I have the following directory layout:

> - src > - main
> - java > - resources
> - sql (scripts for database) > - spring (configuration) > - webapp

Within a ServletContextListener class, I want to access the files under the SQL directory and list them. Basically my problem is with the path, because I know that listing files under a directory in a nutshell is:

File folder = new File(path);
File[] listOfFiles = folder.listFiles();

Maybe I could use the ServletContextEvent Object to try and build a path to resources/sql

public void contextInitialized(ServletContextEvent event) {
    event.getServletContext(); //(getRealPath etc.)
}

Does something exist to set that path in a relative, non-hardcoded way? Something like new File("classpath:sql") (preferably spring if possible) or what should I do with the servletContext to point at resources/sql?

Java Solutions


Solution 1 - Java

I'm assuming the contents of src/main/resources/ is copied to WEB-INF/classes/ inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).

URL sqlScriptUrl = MyServletContextListener.class
                       .getClassLoader().getResource("sql/script.sql");

Solution 2 - Java

Finally, this is what I did:

private File getFileFromURL() {
    URL url = this.getClass().getClassLoader().getResource("/sql");
    File file = null;
    try {
        file = new File(url.toURI());
    } catch (URISyntaxException e) {
        file = new File(url.getPath());
    } finally {
        return file;
    }
}

...

File folder = getFileFromURL();
File[] listOfFiles = folder.listFiles();

Solution 3 - Java

import org.springframework.core.io.ClassPathResource;

...

File folder = new ClassPathResource("sql").getFile();
File[] listOfFiles = folder.listFiles();

It is worth noting that this will limit your deployment options, ClassPathResource.getFile() only works if the container has exploded (unzipped) your war file.

Solution 4 - Java

Just use com.google.common.io.Resources class. Example:

 URL url = Resources.getResource("file name")

After that you have methods like: .getContent(), .getFile(), .getPath() etc

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyamilmedinaView Question on Stackoverflow
Solution 1 - JavaDevView Answer on Stackoverflow
Solution 2 - JavayamilmedinaView Answer on Stackoverflow
Solution 3 - JavasamlewisView Answer on Stackoverflow
Solution 4 - JavagrepView Answer on Stackoverflow