Helius
2020-12-09 660fba5b40303dd661afcc2e2bd54a18d4f53c5c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.matrix.core.tools;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
 
import org.apache.commons.io.IOUtils;
 
/**
 * 文件类型判断工具
 * 
 * @author JIANGYOUYAO
 * @email 935090232@qq.com
 * @date 2017年12月12日
 */
public class FileTypeUtil {
 
    /**
     * 通过文件头的特定字符 校验文件是否为列表中的一种
     * 
     * @author JIANGYOUYAO
     * @email 935090232@qq.com
     * @date 2017年12月20日
     * @param file
     * @param fileTypes
     * @return
     * @throws IOException
     */
    public static boolean checkFileType(File file, List<FileType> fileTypes) throws IOException {
        
        FileInputStream stream = new FileInputStream(file);
        byte[] data = new byte[28];
        IOUtils.readFully(stream, data);
        String fileHead = bytes2hex(data).toUpperCase();
        for (FileType fileType : fileTypes) {
            if (fileHead.startsWith(fileType.getValue())) {
                return true;
            }
        }
        return false;
    }
    
    public static boolean checkFileType(InputStream stream , List<FileType> fileTypes) throws IOException {
        byte[] data = new byte[28];
        IOUtils.readFully(stream, data);
        String fileHead = bytes2hex(data).toUpperCase();
        for (FileType fileType : fileTypes) {
            if (fileHead.startsWith(fileType.getValue())) {
                return true;
            }
        }
        return false;
    }
    
 
    private static String bytes2hex(byte[] b) {
        StringBuffer hexStr = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            hexStr.append(hex);
        }
        return hexStr.toString();
    }
    
    
    /**
     * 获取文件扩展名称
     * 
     * @author JIANGYOUYAO
     * @email 935090232@qq.com
     * @date 2017年12月20日
     * @param file
     * @return
     */
    public static String getFileExtName(File file) {
        String fileName = file.getName();
        String prefix = fileName.substring(fileName.lastIndexOf(".") );
        return prefix;
    }
}