How to access a resource file in src/main/resources/ folder in Spring Boot

In this blog post we will see different ways to access resource file in src/main/resources folder in Spring Boot.

1) Using ResourceLoader

@RestController
public class WelcomeController {

   @Autowired
    private ResourceLoader resourceLoader;

    @GetMapping("/readTextFile")
    public String readTextFile() throws IOException {
        Resource resource = resourceLoader.getResource("classpath:greetings.txt");
        String content = resource.getContentAsString(StandardCharsets.UTF_8);
        return content.formatted("sayHello");
    }

}Code language: Java (java)

2) Using Resource

@RestController
public class WelcomeController {

@Value("classpath:/greetings.txt")
 private Resource resource;

 @GetMapping("/readTextFile")
    public String readTextFile() throws IOException {
        String content = resource.getContentAsString(StandardCharsets.UTF_8);
        return content.formatted("sayHello");
    }

}Code language: Java (java)

3) Using ClassPathResource

@RestController
public class WelcomeController {

   @GetMapping("/readTextFile")
    public String readTextFile() throws IOException {
        
       ClassPathResource classPathResource = new ClassPathResource("greetings.txt");
        String content = classPathResource.getContentAsString(StandardCharsets.UTF_8);
        return content.formatted("sayHello");
    }

}Code language: Java (java)

4) Using ClassLoader

@RestController
public class WelcomeController {


@GetMapping("/readTextFile")
public String readTextFile() throws IOException, URISyntaxException {
        InputStream stream = getClass().getClassLoader().getResourceAsStream("greetings.txt");
        assert stream != null;
        String content = new String(stream.readAllBytes());
        return content.formatted("sayHello");
 }


}Code language: Java (java)
 @GetMapping("/readTextFile")
    public String readTextFile() throws IOException {
        InputStream stream = getClass().getResourceAsStream("/greetings.txt");
        assert stream != null;
        String content = new String(stream.readAllBytes());
        return content.formatted("sayHello");
    }Code language: Java (java)

Note : In above code example, the path should always start with “/”

5) Using ContextClassLoader

@RestController
public class WelcomeController {

 @GetMapping("/readTextFile")
    public String readTextFile() throws IOException {
        InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("greetings.txt");
        assert stream != null;
        String content = new String(stream.readAllBytes());
        return content.formatted("sayHello");
    }

}Code language: Java (java)

Sourcecode for blog post can be downloaded from GitHub

Similar Posts