How to create a permanent directory for my files with spring boot

Viewed 1347

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());
    }
3 Answers

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

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;
}
Related