如何使用 spring 引导为我的文件创建永久目录

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

我正在使用 spring 启动和 spring 内容。我想将我所有的图片和视频存储在一个目录中,但每次我重新 运行 应用程序时,我的代码都会继续创建不同的目录

我有这样的 bean,当我再次 运行 应用程序时它显示空指针,因为目录已经存在但我希望它只创建一次并且每个文件都存储在那里

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

您可以先使用isDirectory() 方法检查目录是否已经存在。如果不存在,则创建一个新的。

一个解决方案是检查目录是否存在:

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

同时还有另一种方法可以实现这一点,当您使用 Spring 引导并相应地使用 spring-content-fs-boot-starter。

根据 https://paulcwarren.github.io/spring-content/refs/release/fs-index.html#_spring_boot_configuration 处的文档,添加

应该就足够了
spring.content.fs.filesystemRoot=/tmp/photo_video_myram

到您的 application.properties 文件。