燕山石化溯源三维电子沙盘-【后端】-服务
13693261870
2023-07-14 db44f336e46825afc855466512065cc08e5790bd
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
package com.yssh.utils;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
 
/**
 * 文件工具类
 * @author WWW
 * @date 2023-06-06
 */
public class FileUtils {
    public final static int SIXTEEN = 16;
 
    public static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
 
    /**
     * 1.获取文件的MD5
     */
    @SuppressWarnings("unused")
    public static String getFileMd5(String filePath) {
        FileInputStream fis = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
 
            fis = new FileInputStream(new File(filePath));
            FileChannel fChannel = fis.getChannel();
            ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024);
 
            while (fChannel.read(buffer) != -1) {
                buffer.flip();
                md.update(buffer);
                buffer.compact();
            }
            byte[] b = md.digest();
 
            return byteToHexString(b);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                if (null != fis) {
                    fis.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
 
    /**
     * 字节码转16进制
     */
    public static String byteToHexString(byte[] tmp) {
        // 每个字节用 16 进制表示的话,使用两个字符,
        char[] str = new char[16 * 2];
 
        // 所以表示成 16 进制需要 32 个字符,表示转换结果中对应的字符位置
        int k = 0;
        // 从第一个字节开始,对 MD5 的每一个字节
        for (int i = 0; i < SIXTEEN; i++) {
            // 转换成 16 进制字符的转换
            byte byte0 = tmp[i];
            // 取字节中高 4 位的数字转换
            str[k++] = HEX_DIGITS[byte0 >>> 4 & 0xf];
            // >>> 为逻辑右移,将符号位一起右移, 取字节中低 4 位的数字转换
            str[k++] = HEX_DIGITS[byte0 & 0xf];
        }
        // 换后的结果转换为字符串
        return new String(str);
    }
}