Q:

Manually get the contents of a file in Spring boot 2

I have a file under src/main/resources/static/css/ called my.css that I'm trying to load as a String, but I can't for the life of me get Spring to find this file that's supposedly statically loaded already in the classpath.
    private String getCss(String cssFileName) {
        try {
            File file = new ClassPathResource("classpath:" + cssFileName + ".css").getFile();
            return new String(Files.readAllBytes(Paths.get(file.getPath())));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "css not found";
    }
}

I've tried various webconfigs, resource loaders, paths and patterns but I just cannot get this to work. How do I find a file in my resources? I'd expect some kind of Resources.getResource("name.type") type of thing which already has a tree with all the resources from the resource folder in it listed.

A:

Using @pandaadb's comment and Spring's auto-wiring functionality to get an instance of the ResourceLoader class:
@Controller
public class Controller {

    @Autowired private ResourceLoader loader;

    private String getCss(String cssFileName) {
        try {
            File file = loader.getResource("classpath:/static/css/" + cssFileName + ".css").getFile();
            return new String(Files.readAllBytes(Paths.get(file.getPath())));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "css not found";
    }
}

The ResourceLoader uses your src/main/resources folder as the root of your "classpath:" search, so simply adding the whole path from that point on works. Don't bother with the classpathloader directly, it gets transformed somehow automatically to one based on the prefix given. This code now finds the file, reads it and converts it to a String.

