2

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

3 回答 3

2

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

于 2018-11-11T18:50:27.197 回答
2

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;
}
于 2018-11-11T18:51:19.057 回答
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.

于 2020-12-02T13:57:47.583 回答