Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

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

public class Main {
    private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    public static String getFileMD5String(File file) {
        if (!file.exists() || file.isFile()) {
            return null;
        }
        MessageDigest messagedigest;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            messagedigest = MessageDigest.getInstance("MD5");
            int len;
            byte[] buf = new byte[1024];
            while ((len = fis.read(buf)) != -1) {
                messagedigest.update(buf, 0, len);
            }
            byte md5Bytes[] = messagedigest.digest();
            StringBuffer stringbuffer = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                stringbuffer.append(HEX_DIGITS[(md5Bytes[i] & 0xf0) >>> 4]);
                stringbuffer.append(HEX_DIGITS[md5Bytes[i] & 0x0f]);
            }
            return stringbuffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}