Reading ClassPath file in Spring Boot/Core Example

(Last Updated On: November 22, 2017)

This below program reads the status.txt file from the classpath, that is src/main/resources in the maven projects using classpathloader in spring core/spring boot projects.

Classpathloader converts it to inputstream, from inputstream we can convert to bufferedinputstream and read the file contents easily.

File Structure:

Here we have status.txt file inside the resources folder, and we have only the value 100 inside the txt file.

 

Reading ClassPath file in Spring Boot/Core Example

Scheduler in Spring Boot with 3 Simple Steps Example

Mention the file name directly inside the classpathresource,

Resource resource = new ClassPathResource(“status.txt”);

If the file inside src/main/resources/config then you can try,

Resource resource = new ClassPathResource(“/config/status.txt”);

(or)

Resource resource = new ClassPathResource(“classpath:/config/status.txt”);

 

 

Reading ClassPath file in Spring Boot/Core Example:

This reads the status.txt file from the classpath (src/main/resources) and print the value 100 in the console.

package online.site;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class ReadClasspathFile {

public static void main(String[] args) {
try {
int i = 0;
String temp = "";

Resource resource = new ClassPathResource("status.txt");
InputStream resourceInputStream = resource.getInputStream();

BufferedReader bfr = new BufferedReader(new InputStreamReader(resourceInputStream));

while ((temp = bfr.readLine()) != null) {
i = Integer.parseInt(temp);
}

bfr.close();

System.out.println(i);
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}

}

 

Spring Boot + Rest Controller Simple Demo

Output:

100

 

Hope I explained you as easy as possible. Feel free to provide your comments if you need any more details.

 

123 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *