Java resource directory files

How to read files from the resources folder in Spring Boot? Example Tutorial

Hello everyone, welcome to the blog post. In this article, we are going to take a look at a frequently asked question in spring boot on how to read files from the resources folder. A resource is any file that contains information relevant to your project, including configuration files, picture files, data files, or other types of files. In this article, we will look at various methods and techniques that both spring boot and ordinary Java code allow us to read a file from the resources directory. Our goal is not simply to list these approaches; rather, we will describe each strategy with the help of an example so that, everyone can easily grasp the topic. Without further ado, let’s get started.

5 Ways to Read files from the resources folder in Spring Boot

There are many ways to read a file from the resource folder in Spring Boot but following are the most popular ways to read a file;

• Using Spring Resource Interface

We will see each one of them in detail with code example, so that you can use them in your code. In the upcoming sections we will discuss the above-mentioned methods in great detail;

1. Using Spring Resource Interface

The great thing about spring Resource Interface is, it hides the low-level details from its user, but still provides a uniform way to handle every kind of resource that it supports. Let’s first take a look at the interface itself.

public interface InputStreamSource < InputStream getInputStream() throws IOException; > public interface Resource extends InputStreamSource < boolean exists(); boolean isOpen(); URL getURL() throws IOException; File getFile() throws IOException; Resource createRelative(String relativePath) throws IOException; String getFilename(); String getDescription(); >

The above interface has following methods:

exists(): boolean isOpen(): boolean getURL(): URL getFile(): File createRelative(): Resource getFilename(): String getDescription(): String

I’m sure many of you already know we can’t create an object or instance of an interface. Instead, we require a class that provides its implementation. Many classes implement Resource interfaces in Spring, these are UrlReource , FileSystemResource , ClassPathResource , ServletContextResource , and InputStreamResource .

Читайте также:  How to create module in python

Here we will focus only on one implementation class i.e. ClassPathResource.

Using ClassPathResource Implementation

As the name suggests it represents a resource being loaded from a classpath. One thing to note here is we can easily switch to java standard File or InputStream from Resource .

For better understanding purposes, let’s create a simple Java project to demonstrate it with an example.

1) We created a simple text file that holds companies’ names as following

Google, Facebook, Twitter, Samsung, Microsoft, Folio3, AvanzaSolutions, Apple, AWS, bitspro

2) We created a simple Java class and spring boot REST API endpoint to demonstrate it. (Note: there is no need to have a REST endpoint for it. But for the sake of simplicity we are using Spring Boot)

public static void main(String[] args) throws IOException < Resource companyDataResource = new ClassPathResource("companies.txt"); File file = companyDataResource.getFile(); System.out.println("Filename: " + file.getName()); System.out.println("Executable: " + file.canExecute()); System.out.println("Readable: " + file.canRead()); String content = new String(Files.readAllBytes(file.toPath())); System.out.println(content); >
> Task:Demo.main() Filename: companies.txt Executable: false Readable: true Google, Facebook, Twitter, Samsung, Microsoft, Folio3, AvanzaSolutions, Apple, AWS, bitspro.

As you can see we can read the content of our file companies.txt with the help of ClassPathResource. But one has to keep in mind that ClassPathResource requires an absolute path. But in case you want to use a relative path you can pass a second argument as a class name. The given path should be relative to the class.

new ClassPathResource("../../data/students.txt", Students.class).getFile();

In the above example, the path to the employee’s file is relative to the Student’s class.

3. Using Spring @Value annotation

Using the @Value annotation, we can inject a classpath resource directly into a Spring bean. One thing to note here is it loads the file eagerly.

@Value(“classpath. /../data/students.txt”) Resource resourceFile; //Somewhere in the code File file = resource.getFile();

4. Using ResourceLoader

There is another way one can load their resources using ResourceLoader. It is also helpful in case you want lazy loading. We can provide a fully qualified URL or file path «file:Directory:/folder1/folder2/folder3/students.txt» or «classpath:students.txt».

Читайте также:  Return в функции java

ResourceLoader also supports relative file paths such as «WEB-INF/students.txt» .

@Autowired ResourceLoader resourceLoader; Resource res = resourceLoader.getResource("classpath:companies.txt"); File file = res.getFile();

5. Using Spring REST API

Here is another way to download and read file from the resource folder in Spring Boot.

@RestController @RequestMapping("/api/v1/resouces") public class AppResources < @Autowired ResourceLoader resourceLoader; @RequestMapping("/resources") public ResponseEntity getResourceInfo() throws IOException < Resource res = resourceLoader.getResource("classpath:companies.txt"); String output = ""; File file = res.getFile(); output + hljs-attribute" style="color: #6a8759;">Filename: " + file.getName() + " \n Executable: " + file.canExecute() + "\n Readable: \" + file.canRead()"; String content = new String(Files.readAllBytes(file.toPath())); System.out.println(content); return new ResponseEntity<>(content,HttpStatus.OK); > >
Google, Facebook, Twitter, Samsung, Microsoft, Folio3, AvanzaSolutions, Apple, AWS, bitspro.

It is designed to be used by objects that can return Resource instances. Since all application contexts provide the ResourceLoader interface, Resource instances may be retrieved from any application context.

6. Using ResourceUtils

Here is another way to load or read files from the resource folder in Spring boot application using ResourceUtils class.

import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.util.concurrent.TimeUnit; public class Demo < public static void main(String[] args) throws IOException < File file = loadEmployeesWithSpringInternalClass(); String content = new String(Files.readAllBytes(file.toPath())); System.out.println(content); > public static File loadEmployeesWithSpringInternalClass() throws FileNotFoundException < return ResourceUtils.getFile( "classpath:companies.txt"); > >
> Task :Demo.main() Google, Facebook, Twitter, Samsung, Microsoft, Folio3, AvanzaSolutions, Apple, AWS, bitspro.

That’s all about 5 ways to read a file from the resource folder in Spring boot application and Java. Thanks for staying with us, with this we reach the end of our article. In this brief blog, we examined several methods for utilizing Spring to access and read a resource via Resource Interface, ClassPathResource , @Value annotation, ResourceLoader , and ResourceUtils . In addition to learning these techniques, we also practice them by using examples.

To practice, we built a simple text file called «companies.txt» containing the names of several firms in it. To read this data file, we applied each method separately. I sincerely hope that this simple presentation has helped you comprehend the subject matter.

I also hope by now you will be in a position to face any challenge related to reading files using Spring Boot.

  • Top 5 Courses to Learn and Master Spring Cloud
  • Difference between applicatio.propertis and application.yml
  • Difference between Spring Boot and Spring Cloud
  • 10 Example of WebClient in Spring Boot
  • 10 Books Java Developers Should Read
  • Difference between Spring Framework and Spring Boot
  • How to test Spring Boot application in Java?
  • Top 5 Courses to learn Spring Cloud and Microservices
  • 5 Free Courses to Learn Spring Framework
  • Top 10 Courses to learn Microservices in Java with Spring Boot
  • How to log SQL statement in Spring Boot
  • 5 Spring Books Experienced Java Developer Should Read
  • Top 5 Books and Courses to learn RESTful Web Services in Java
  • How to use @RequestBody and @ResponseBody in Spring
  • 5 Courses to Learn Spring Security in depth
  • Top 5 Frameworks Java Developer Should Know
  • 10 Projects you can build to learn Spring Boot?
  • Top 15 Spring Boot Interview Questions for Java Developers
  • 10 Tips to become a better Java Developer
  • 10 Advanced Spring Boot Courses for Experienced Java Developers
  • 10 Spring Boot Annotations Java Developers should know

Источник

Java — чтение файла из папки ресурсов

В этом руководстве мы покажем вам, как читать файл из папки resources или пути к классам как в среде выполнения, так и в среде модульного тестирования. Попробуйте поместить файл в папку src/main/resources и прочитайте файл со следующими фрагментами кода:

File file = new File( getClass().getClassLoader().getResource("database.properties").getFile() );
InputStream inputStream = getClass() .getClassLoader().getResourceAsStream("database.properties");

Note
Вас может заинтересовать этотgetResourceAsStream in static method

1. Каталог проектов

Просмотрите структуру проекта Maven.

project directory

2. Прочитать файл из папки ресурсов

datasource.url=jdbc:mysql://localhost/example?useSSL=false datasource.username=root datasource.password=password datasource.driver-class-name=com.mysql.jdbc.Driver

Прочтите файл database.properties и распечатайте его содержимое.

package com.example; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URL; public class Application < public static void main(String[] args) throws IOException < Application main = new Application(); File file = main.getFileFromResources("database.properties"); printFile(file); >// get file from classpath, resources folder private File getFileFromResources(String fileName) < ClassLoader classLoader = getClass().getClassLoader(); URL resource = classLoader.getResource(fileName); if (resource == null) < throw new IllegalArgumentException("file is not found!"); >else < return new File(resource.getFile()); >> private static void printFile(File file) throws IOException < if (file == null) return; try (FileReader reader = new FileReader(file); BufferedReader br = new BufferedReader(reader)) < String line; while ((line = br.readLine()) != null) < System.out.println(line); >> > >
datasource.url=jdbc:mysql://localhost/example?useSSL=false datasource.username=root datasource.password=password datasource.driver-class-name=com.mysql.jdbc.Driver

Источник

Оцените статью