簡體   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