3

I am working with spring boot and spring content. I want to store all my pictures and videos in one directory but my code continues to create different dir every time I rerun the application

I have such bean and when I run the app again it shows null pointer because the dir already exists but I want it to create it just once and every file is stored there

every time i run this tries to create the dir again
    @Bean
     File filesystemRoot() {
        try {
            return Files.createDirectory(Paths.get("/tmp/photo_video_myram")).toFile();
        } catch (IOException io) {}
        return null;
    }

    @Bean
    FileSystemResourceLoader fileSystemResourceLoader() {
        return new FileSystemResourceLoader(filesystemRoot().getAbsolutePath());
    }
Paul Warren
  • 2,411
  • 1
  • 15
  • 22
valik
  • 2,014
  • 4
  • 24
  • 55

3 Answers3

3

You can use isDirectory() method first to check if the directory already exists. In case it does not exist, then create a new one.

3

One solution, would be to check if the directory exists:

@Bean
File filesystemRoot() {
  File tmpDir = new File("tmp/photo_video_myram");
  if (!tmpDir.isDirectory()) {
    try {
      return Files.createDirectory(tmpDir.toPath()).toFile();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return tmpDir;
}
Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240
2

Meanwhile there is another way to achieve this, when you use Spring Boot and accordingly spring-content-fs-boot-starter.

According to the documentation at https://paulcwarren.github.io/spring-content/refs/release/fs-index.html#_spring_boot_configuration it should be sufficient to add

spring.content.fs.filesystemRoot=/tmp/photo_video_myram

to your application.properties file.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
marcel.s
  • 61
  • 5