Read File from the Classpath in the Spring
In this tutorial, we will see different ways to read file from the classpath in the Spring.
1). Using ResourceUtils
2). Using ClassPathResource
3). Using @Value
4). Using ResourceLoader
5). Reading as an InputStream
1). Using ResourceUtils
The ResourceUtils class has Utility methods for resolving resource locations to files in the file system. Consider using Spring's Resource abstraction in the core package for handling all kinds of file resources in a uniform manner.
ResourceLoader's getResource() method can resolve any location to a Resource object, which in turn allows one to obtain a java.io.File in the file system through its getFile() method.
import org.springframework.util.ResourceUtils;
File file = ResourceUtils.getFile("classpath:application.properties")
System.out.println("The File Found :" + file.exists());
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println("the file contents are : ");
System.out.println(content);
2). Using ClassPathResource
The ClassPathResource removes some boilerplate for selecting between the thread's context classloader and the default system classloader.
File file = new ClassPathResource("config.csv", this.getClass().getClassLoader()).getFile();
3). Using @Value
We can use @Value annotation to load the file from classpath as a resource.
@Value("classpath:config.csv")
Resource resourceFile;
4). Using ResourceLoader
ResourceLoader is implemented by all concrete ApplicationContexts so that we can depend on ApplicationContext.
ApplicationContext context;
public Resource loadEmployees() {
return context.getResource("classpath:config.csv");
}
5). Reading as an InputStream
InputStream resource = new ClassPathResource(
"orderdata/orders.csv").getInputStream();
try ( BufferedReader reader = new BufferedReader(
new InputStreamReader(resource)) ) {
String orders = reader.lines()
.collect(Collectors.joining("\n"));
System.out.println("the orders are:");
System.out.println(orders);
}
Post/Questions related to Read File from the Classpath in the Spring
How do you load properties files from the Resources folder in Java?
What is the Java Resources folder?
How do I read a file from the Resources folder in spring boot?
How do I read a resource folder?
How to read a file from the src folder in java?
Spring-boot read file from external folder
Spring-boot read file from the file system
How to load the file from classpath in spring?
What is classpath in spring?
What is classpath in the spring application context?
How to Read the file from resources folder in Java
In this article, we have seen Read File from the Classpath in the Spring.
0 Comments
Post a Comment