Java - 校验文件内容是否修改

思路:使用MD5对文件内容进行加密, 得到字符串进行比较;-- 不可使用文件大小判断;

借鉴:参考Nacos源码,Nacos底层对配置文件的校验使用的是此方法

MD5Utils工具类:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class MD5Utils {

    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f'};
    
    private static final ThreadLocal MESSAGE_DIGEST_LOCAL = new ThreadLocal() {
        @Override
        protected MessageDigest initialValue() {
            try {
                return MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                return null;
            }
        }
    };
    
    /**
     * Calculate MD5 hex string.
     *
     * @param bytes byte arrays
     * @return MD5 hex string of input
     * @throws NoSuchAlgorithmException if can't load md5 digest spi.
     */
    public static String md5Hex(byte[] bytes) throws NoSuchAlgorithmException {
        try {
            MessageDigest messageDigest = MESSAGE_DIGEST_LOCAL.get();
            if (messageDigest != null) {
                return encodeHexString(messageDigest.digest(bytes));
            }
            throw new NoSuchAlgorithmException("MessageDigest get MD5 instance error");
        } finally {
            MESSAGE_DIGEST_LOCAL.remove();
        }
    }
    
    /**
     * Calculate MD5 hex string with encode charset.
     *
     * @param value  value
     * @param encode encode charset of input
     * @return MD5 hex string of input
     */
    public static String md5Hex(String value, String encode) {
        try {
            return md5Hex(value.getBytes(encode));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    /**
     * Convert a byte array into a visible string.
     */
    public static String encodeHexString(byte[] bytes) {
        int l = bytes.length;
        
        char[] out = new char[l << 1];
        
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & bytes[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & bytes[i]];
        }
        
        return new String(out);
    }
}

FileTest测试工具类:

public class FileTest {

    public static void main(String[] args) throws NoSuchAlgorithmException {
        File file1 = new File("C:\\Users\\Desktop\\文件1.txt");
        File file2 = new File("C:\\Users\\Desktop\\文件2.txt");
        File file3 = new File("C:\\Users\\Desktop\\文件3.txt");
        System.out.println(file1.length());
        System.out.println(file2.length());
        System.out.println(file3.length());

        String file1Md5 = MD5Utils.md5Hex(fileToBytes(file1)); //c4ca4238a0b923820dcc509a6f75849b
        System.out.println(file1Md5);
        String file2Md5 = MD5Utils.md5Hex(fileToBytes(file2)); //c4ca4238a0b923820dcc509a6f75849b
        System.out.println(file2Md5);
        String file3Md5 = MD5Utils.md5Hex(fileToBytes(file3)); //cfcd208495d565ef66e7dff9f98764da
        System.out.println(file3Md5);
    }

    /**
     * 文件转字节
     * @param file
     * @return
     */
    public static byte[] fileToBytes(File file) {
        FileInputStream in = null;
        ByteArrayOutputStream out = null;
        byte[] buffer = null;
        try{
            in = new FileInputStream(file);
            out = new ByteArrayOutputStream();
            int n;
            byte[] b = new byte[1024];
            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n);
            }
            buffer = out.toByteArray();
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            try {
                if (in != null){
                    in.close();
                }
                if (out != null){
                    out.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return buffer;
    }
}

你可能感兴趣的:(文件操作相关,java)