SoFunction
Updated on 2025-05-19

How to convert file content to MD5 hash value

Convert Java file content to MD5 hash value

To read itfilesThe content in the list is converted to an MD5 hash value, which you can traverse one by one.filesElements in the list, compute the content of each element into an MD5 hash value.

A complete Java sample code

Shows how to implement this function:

import ;
import ;
import ;
import ;
import ;
import ;
import ;

class CheckHelper {
    public static String getOcetString(byte[] buffer, int bytesRead) {
        return new String(buffer, 0, bytesRead);
    }
}

public class FilesToMD5 {
    public static String calculateMD5(String input) {
        try {
            // Get an MD5 message digest instance            MessageDigest md = ("MD5");
            // Calculate the MD5 hash value of the input string            byte[] digest = (());
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = (0xFF & b);
                if (() == 1) {
                    ('0');
                }
                (hex);
            }
            return ();
        } catch (NoSuchAlgorithmException e) {
            // If the MD5 algorithm is not available, a runtime exception is thrown            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String path = "path/to/your/";
        int blockSize = 1024;
        long fileLength = 0;
        List<String> files = new ArrayList<>();

        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path))) {
            byte[] buffer = new byte[blockSize];
            int bytesRead;
            while ((bytesRead = (buffer)) != -1) {
                fileLength += bytesRead;
                ((buffer, bytesRead));
            }
        } catch (IOException e) {
            ();
        }

        // traverse the files list and calculate the MD5 hash value of each element        for (String content : files) {
            String md5 = calculateMD5(content);
            ("content: " + content);
            ("MD5 hash: " + md5);
        }
    }
}    

Code explanation

calculateMD5 method

  • With the help("MD5")Get an MD5 message digest instance.
  • use(())Calculates the MD5 hash value of the input string.
  • Convert the calculated byte array into a hexadecimal string.

mainmethod

  • Read the file content tofilesList.
  • TraversalfilesList, call each elementcalculateMD5Method calculates the MD5 hash value and prints the result out.

Things to note

  • Want to"path/to/your/"Replace with the actual file path.
  • This code is correctfilesEach element in the list calculates the MD5 hash value separately. If you want to calculate the MD5 hash value of the entire file content, you need to merge all the elements before calculating.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.