{{announcement.body}}
{{announcement.title}}

Spring Boot: Reading Resources

DZone 's Guide to

Spring Boot: Reading Resources

Learn how to read files from the resources folder in a Spring Boot application.

· Java Zone ·
Free Resource
Learn how to read files from the resources folder in a Spring Boot application.

Reading files from a Spring Boot application is possible through Java 8 NIO API. This article demonstrates how to read files from the resources folder in a Spring Boot application, which is running as a standalone application or inside the Docker container. 

You may also like: Working With Resources in Spring

Create a Project

Generate a Gradle or Maven project using the Spring Initializer. Create folder and files inside the resources folder as required.

Image title

Create a Pseudo File System

We are trying to read metafiles folder contents from the above structure. We need to convert the file path to URI resource. Create a new file system for URI resource. Since  FileSystem is Closable, we are able to place initialize the jarFileSystem within the try block.

Java




xxxxxxxxxx
1


 
1
public void readFolderFromJar() throws Exception {
2
    String relativePath = "metafiles";
3
    URI resource = getClass().getClassLoader().getResource(relativePath).toURI();
4
    try (FileSystem jarFileSystem = FileSystems.newFileSystem(resource, Collections.emptyMap())) {
5
        String[] jarPath = resource.toString().split("!", 2);
6
        String jarReference = jarPath[1].replace("!", "");
7
        readContent(jarFileSystem.getPath(jarReference));
8
    }
9
}



Recursively Traverse

If the path is a directory, then recursively call readContent function until we encounter the individual files. Let us use NIO API Files. Files.list lists would list out paths lazily. 

Java




xxxxxxxxxx
1
39


 
1
public void readContent(Path path)
2
    {
3
        try
4
        {
5
            Stream<Path> list = Files.list(path);
6
            List<Path> paths = list.parallel().collect(Collectors.toList());
7
            paths.stream().parallel().forEach(filePath -> {
8
                if (Files.isDirectory(filePath))
9
                {
10
                    readContent(filePath);
11
                }
12
                else
13
                {
14
                    try
15
                    {
16
                        String fileName = filePath.toString().split("classes")[1];
17
                        String content = readFile(filePath);
18
                        logger.debug("File: "+fileName+": Content: "+content);
19
                    }
20
                    catch (Exception e)
21
                    {
22
                        logger.error("Unable to read file " + e.getMessage());
23
                    }
24
                }
25
            });
26
        }
27
        catch (Exception e)
28
        {
29
            logger.error("Unable to read file " + e.getMessage());
30
        }
31
    }
32
Read content
33
Read content of files from path using Files.readAllBytes. 
34
 
          
35
   private String readFile(Path path) throws IOException
36
    {
37
        byte[] encoded = Files.readAllBytes(path);
38
        return  new String(encoded, Charset.forName("UTF-8"));
39
    }



Test Run

Run your Spring Boot project using the traditional approach shown below. Here, resources/metafiles will be part of "jar," and still, we will be able to read the contents of these files. 

 java -jar demo-0.0.1-SNAPSHOT.jar 

Hope you enjoyed!

Further Reading

Working With Resources in Spring

Put a Spring in Your Step: Spring Framework Tutorials

A Guide to Spring Framework Annotations

Topics:
java 8 ,streams ,nio ,file api ,resource ,jar ,java ,spring boot

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}