package top.imwork.window.silos.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * Copyright (C), 2015-2025
 * FileName: FileUtils
 * Author<作者姓名>:   stars
 * CreateTime<创建时间>:   2025/12/15 15:59
 * UpdateTime<修改时间>:   2025/12/15 15:59
 * Description〈功能简述〉: 文件工具类
 * History<历史描述>:
 * Since<版本号>: 1.0.0
 */
public class FileUtils {

    /**
     * 获取文件扩展名
     */
    public static String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf('.') == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf('.')).toLowerCase();
    }

    /**
     * 计算文件哈希值（SHA-256）
     */
    public static String calculateFileHash(File file) throws IOException {
        try (FileInputStream fis = new FileInputStream(file)) {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] buffer = new byte[8192];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                digest.update(buffer, 0, bytesRead);
            }

            byte[] hashBytes = digest.digest();
            StringBuilder hexString = new StringBuilder();

            for (byte hashByte : hashBytes) {
                String hex = Integer.toHexString(0xff & hashByte);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("不支持SHA-256算法", e);
        }
    }
}