Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.security.DigestInputStream;
import java.security.MessageDigest;

public class Main {

    public static boolean checkMd5sum(File file, String checkCode) throws IOException {
        DigestInputStream dInput = null;
        try {
            FileInputStream fInput = new FileInputStream(file);
            dInput = new DigestInputStream(fInput, getMd5Instance());
            byte[] buf = new byte[8192];
            while (dInput.read(buf) > 0) {
            }
            byte[] bytes = dInput.getMessageDigest().digest();
            return bytes2hex(bytes).equals(checkCode);
        } finally {
            closeQuietly(dInput);
        }
    }

    private static MessageDigest getMd5Instance() {
        try {
            return MessageDigest.getInstance("md5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String bytes2hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0XFF);
            if (hex.length() == 1) {
                sb.append("0").append(hex);
            } else {
                sb.append(hex);
            }
        }
        return sb.toString();
    }

    private static void closeQuietly(OutputStream output) {
        try {
            if (output != null) {
                output.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }

    private static void closeQuietly(InputStream input) {
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }
}