繁体   English   中英

如何使用 Java/Spring 自动管理文件系统目录树?

[英]How to automatically manage a file system directory tree using Java/Spring?

我正在尝试为 Spring Boot web 应用程序创建文件系统集成。

我有一个当前有效的解决方案,将文件内容存储在文件系统中,并将文件名和位置存储在数据库中。 数据库表

磁盘内容:

图片

我正在尝试找到一种将保存的文件分成文件夹的方法。 根文件夹应该是“文件系统”,并且文件应该被分成多个文件夹,一个文件夹包含不超过 500 个文件。

这样做的正确方法是什么?
我可以使用 Spring 或 Java 内置的目录树管理器吗?

我目前的解决方案如下。

数据库文件

@Entity
public class DBFile {

    @Id
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "location")
    private String location;
}

文件系统存储库

@Repository
public class FileSystemRepository {
    public static final String RESOURCES_ROOT_DIR = "/file-system/";

    public String save(byte[] content, String fileName, String contentType) throws IOException {
        Path path = getPath(fileName, contentType);
        Files.createDirectories(path.getParent());
        Files.write(path, content);
        return path.toAbsolutePath().toString();
    }

    public FileSystemResource findInFileSystem(String location) {
        return new FileSystemResource(Paths.get(location));
    }

    public void deleteInFileSystem(String location) throws IOException {
        Files.delete(Paths.get(location));
    }

    private Path getPath(String fileName, String contentType) {
        Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
        String subDirectory;
        if (contentType.startsWith("image/")) {
            subDirectory = "images/";
        } else {
            subDirectory = "files/";
        }
        return Paths.get(path + RESOURCES_ROOT_DIR + subDirectory + new Date().getTime() + "-" + fileName);
    }
}

文件系统服务

@Service
public class FileSystemService {

    private final FileSystemRepository fileSystemRepository;
    private final DBFileRepository dbFileRepository;

    public Long save(byte[] bytes, String imageName, String contentType) {
        try {
            String location = fileSystemRepository.save(bytes, imageName, contentType);

            return dbFileRepository.save(new DBFile(imageName, location))
                .getId();
        } catch (IOException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
        }
    }

    public FileSystemResource find(Long id) {
        DBFile image = dbFileRepository.findById(id)
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));

        return fileSystemRepository.findInFileSystem(image.getLocation());
    }

    public void delete(Long id) {
        DBFile image = dbFileRepository.findById(id)
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));

        try {
            fileSystemRepository.deleteInFileSystem(image.getLocation());
        } catch (IOException e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }

        dbFileRepository.delete(image);
    }
}

我在这个问题上苦苦挣扎了很长一段时间,但现在我找到了一个可能的解决方案,我的一位好同事发给了我。

一个可能的解决方案是创建一个散列目录结构。

更多信息和我使用的示例可以在这里找到: https://medium.com/eonian-technologies/file-name-hashing-creating-a-hashed-directory-structure-eabb03aa4091

我从文件名创建路径的最终解决方案:

  private static Path getPath(String fileName) {
    Path root = FileSystems.getDefault().getPath("").toAbsolutePath();
    int hash = fileName.hashCode();

    int mask = 255;
    int firstDir = hash & mask;
    int secondDir = (hash >> 8) & mask;

    String path = root +
        File.separator +
        RESOURCES_ROOT_DIR +
        File.separator +
        String.format("%03d", firstDir) +
        File.separator +
        String.format("%03d", secondDir) +
        File.separator +
        getDatedFileName(fileName);

    return Paths.get(path);
}

private static String getDatedFileName(String fileName) {
    LocalDateTime today = LocalDateTime.now();
    return String.format("%s-%s-%s_%s_%s_%s-%s",
        today.getYear(),
        today.getMonthValue(),
        today.getDayOfMonth(),
        today.getHour(),
        today.getMinute(),
        today.getSecond(),
        fileName);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM