DEV Community

DzifaHodey
DzifaHodey

Posted on

NoSuchFileException - How to avoid it when adding resources to a Spring Boot Application

Have you ever tried reading resources (json files, htm templates, text files etc) in your Spring Boot project, but got a java.nio.file.NoSuchFileException?
confused
The NoSuchFileException occurs if the file is not in the specified location. A similar exception that occurs is the FileNotFoundException.

1. Loading Files from a directory

A common approach developers use to add resources is to place the files in the src/main/resources/ directory, and then read the files from that path.
Although not the best practice, this approach works if the project is run locally. This is because the project directory is used as the current working directory during runtime.

For example, using the code below, I can read user data from a file and save the value in a string.

application.properties

filePath=src/main/resources/filename.txt
Enter fullscreen mode Exit fullscreen mode

ReadUserDataFromFile.java

public class ReadUserDataFromFile {
   @Value("${filePath}")
   private String dataFilePath;

   public String readDataFile() throws IOException {
      String data = new String(Files.readAllBytes(Paths.get(filePath)));
     return data;
    }
}
Enter fullscreen mode Exit fullscreen mode

The file is successfully read if it is in the src/main/resources/ directory.

Now, if the project is packaged as a JAR file, the NoSuchFileException will be thrown when trying to read the file. This happens because filename.txt is at the root folder of the JAR and it cannot be accessed using the file path.

2. Creating a Resource object

A better approach and a solution to the NoSuchFileException is to create a org.springframework.core.io.Resource object in your class and set the value to point to the file.
Example:

ReadUserDataFromFile.java

public class ReadUserDataFromFile {
   @Value("classpath:filename.txt")
   private Resource dataFile;

   public String readDataFile() throws IOException {
      String data = new String(dataFile.getInputStream().readAllBytes());
      return data;
    }
}
Enter fullscreen mode Exit fullscreen mode

With this approach, the file can be read both locally and from JAR file.

Discussion (0)