简体   繁体   English

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

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

I am trying to create a file system integration for a Spring Boot web application.我正在尝试为 Spring Boot web 应用程序创建文件系统集成。

I have a currently working solution that stores the file content in file system and file name and location in a database.我有一个当前有效的解决方案,将文件内容存储在文件系统中,并将文件名和位置存储在数据库中。 数据库表

Contents on disk:磁盘内容:

图片

I am trying to find a way to separate saved files into folders.我正在尝试找到一种将保存的文件分成文件夹的方法。 The root folder should be "file-system" and files should be separated into folders in a way that one folder contains no more than 500 files.根文件夹应该是“文件系统”,并且文件应该被分成多个文件夹,一个文件夹包含不超过 500 个文件。

What is the correct way to do this?这样做的正确方法是什么?
Is there a directory tree manager that is built in to Spring or Java that I can use?我可以使用 Spring 或 Java 内置的目录树管理器吗?

My current solution is below.我目前的解决方案如下。

DBFile :数据库文件

@Entity
public class DBFile {

    @Id
    private Long id;

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

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

FileSystemRepository :文件系统存储库

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

FileSystemService :文件系统服务

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

I was struggling with this issue for quite a while, but now I found a possible solution that a nice colleague of mine sent to me.我在这个问题上苦苦挣扎了很长一段时间,但现在我找到了一个可能的解决方案,我的一位好同事发给了我。

A possible solution is to create a hashed directory structure.一个可能的解决方案是创建一个散列目录结构。

More information and also an example that I used can be found here: https://medium.com/eonian-technologies/file-name-hashing-creating-a-hashed-directory-structure-eabb03aa4091更多信息和我使用的示例可以在这里找到: https://medium.com/eonian-technologies/file-name-hashing-creating-a-hashed-directory-structure-eabb03aa4091

My final solution to create a path from file name:我从文件名创建路径的最终解决方案:

  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.

相关问题 如何使用Java在文件系统上使用索引管理文件 - how to manage files with indexes on a file system using java 如何使用 Java 8 在 Spring Boot 中获取目录(不是文件)的完整系统路径 - How to get the full system path of a directory (not file) in Spring boot with Java 8 使用堆栈在Java中制作文件/目录树 - Using stack to make file/directory tree in Java 如何使用Spring Boot Rest Java EE项目正确管理对文件的写入? - How to manage writing to file correctly using Spring Boot Rest Java EE project? 如何在Java EE环境中管理数据库和文件系统的事务? - How to manage transaction for database and file system in Java EE environment? 如何返回 spring controller 中的文件目录(源树) - How to return a file directory(source tree) in spring controller 如何在Java中自动设置目录并创建新文件? - How do I automatically set a directory and create a new file in java? Java - 使用 ProcessBuilder directory() 时系统找不到指定的文件 - Java - The system cannot find the file specified when using ProcessBuilder directory() 如何使用Spring读取文件系统 - How to read a file system using Spring 如何管理多个Windows系统 - Java(Swing) - How to manage multiple windows system - Java(Swing)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM