In a Spring Boot project, you keep your static assets in the src/main/resources folder. They'll be bundled, untouched, into your final WAR file when you build your project for deployment. But you can't reference them like you would regular files, with a path name. You need to use a ResourceLoader to retrieve a reference to the file.
Inject a ResourceLoader into your class file using @AutoWired
:
@Controller
public class WarResourceController {
@Autowired
private ResourceLoader resourceLoader;
// ...
}
ResourceLoader reads from the root of the resources folder. When using the ResourceLoader,
you must prefix the name and sub-path of the file to be read with classpath:
. Thusly, to read
src/main/resources/static/test.txt, we use resourceLoader.getResource()
to return a
Resource
from classpath:static/test.txt:
String filename = "static/test.txt";
String warResourceName = "classpath:" + filename;
Resource resource = resourceLoader.getResource(warResourceName);
From there, we can obtain a File
reference to the object with resource.getFile()
:
File file = resource.getFile();
And we can use the File object in whatever read operation we want:
byte[] bytes = new FileInputStream(file).readAllBytes();
String content = new String(bytes, StandardCharsets.UTF_8);
Our entire controller class looks something like this:
@Controller
public class WarResourceController {
@Autowired
private ResourceLoader resourceLoader;
@GetMapping("/war-resource")
ResponseEntity<String> getResponse() {
try {
String filename = "static/test.txt";
String warResourceName = "classpath:" + filename;
Resource resource = resourceLoader.getResource(warResourceName);
File file = resource.getFile();
byte[] bytes = new FileInputStream(file).readAllBytes();
String content = new String(bytes, StandardCharsets.UTF_8);
return ResponseEntity.ok(content);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().build();
}
}
}