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

public class FileCheckTypeUtil {
    private static Logger logger = LogManager.getLogger(FileCheckTypeUtil.class);
    static Map 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));
    }
}
文件类型需要提前穷举

你可能感兴趣的:(Java常见问题处理)