Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.util.Base64;

import java.io.BufferedInputStream;

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

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import java.security.MessageDigest;

public class Main {
    public static String smallFileSha1(File file) {
        InputStream inputStream = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            inputStream = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[1024];
            int nRead = 0;
            while ((nRead = inputStream.read(buffer)) != -1) {
                md.update(buffer, 0, nRead);
            }
            byte[] digest = md.digest();
            byte[] blockBytes = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(1).array();
            byte[] result = ByteBuffer.allocate(4 + digest.length).put(blockBytes, 0, 4)
                    .put(digest, 0, digest.length).array();
            return Base64.encodeToString(result, Base64.URL_SAFE | Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}