Java通过文件头获取文件类型

public class FileCheckTypeUtil {
    private static Logger logger = LogManager.getLogger(FileCheckTypeUtil.class);
    static Map<String,String> map = null;
    static {
        map =new HashMap<>();
        map.put("FFD8FF","jpg");
        map.put("89504E","png");
        map.put("474946","gif");
        map.put("524946","webp");
        map.put("000001","ico");
        map.put("424D36","bmp");
        map.put("00000A","tga");
        map.put("49492A","tif");
    }

    private  static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }



    private  static  String checkType(String code){
        return map.get(code);
    }

    /**
     * 获得图片后缀
     * @param path
     * @return
     */
    public static String getType(String path){
        String type ="";
        FileInputStream fileInputStream =null;
        try {
            fileInputStream = new FileInputStream(path);
            byte[] b = new byte[3];
            fileInputStream.read(b, 0, b.length);
            String code = bytesToHexString(b);
            code = code.toUpperCase();
            type = checkType(code);

        }catch (Exception e){
            logger.error("获取文件格式异常");
        }finally {
            if(fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return type;
    }

    public static void main(String[] args) throws IOException {
        String path = "E:\\redis64-2.8.9.zip";
        System.out.println(getType(path));
    }
}
文件类型需要提前穷举
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值