How can Spring Boot obtain the file path of a resource?

In Spring Boot, you can use ResourceLoader to access the file path of a resource.

@Autowired
private ResourceLoader resourceLoader;

public void getResourcePath() throws IOException {
    Resource resource = resourceLoader.getResource("classpath:myfile.txt");
    String filePath = resource.getFile().getAbsolutePath();
    System.out.println("Resource file path: " + filePath);
}

In the example above, the method resourceLoader.getResource() can take a resource path as a parameter, where the prefix classpath: indicates that the resource file is located in the classpath. The getFile() method is used to obtain the absolute path of the resource file.

bannerAds