计算文件的MD5值(Java & Rust)

Java

public class TestFileMD5 {

    public final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
        "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    /**
     * 获取文件的MD5值
     * @param file
     * @return
     */
    public static String getFileMD5(File file){
        String md5 = null;
        FileInputStream fis = null;
        FileChannel fileChannel = null;
        try {
            fis = new FileInputStream(file);
            fileChannel = fis.getChannel();
            MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());

            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(byteBuffer);
                md5 = byteArrayToHexString(md.digest());
            } catch (NoSuchAlgorithmException e) {

                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }finally{
            try {
                fileChannel.close();
                fis.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }

        return md5;
    }

    /**
     * 字节数组转十六进制字符串
     * @param digest
     * @return
     */
    private static String byteArrayToHexString(byte[] digest) {

        StringBuffer buffer = new StringBuffer();
        for(int i=0; i<digest.length; i++){
            buffer.append(byteToHexString(digest[i]));
        }
        return buffer.toString();
    }

    /**
     * 字节转十六进制字符串
     * @param b
     * @return
     */
    private static String byteToHexString(byte b) {
        //    int d1 = n/16;
             int d1 = (b&0xf0)>>4;

        //     int d2 = n%16;
             int d2 = b&0xf;
             return hexDigits[d1] + hexDigits[d2];
    }

    public static void main(String [] args) throws Exception{
        System.out.println("-----测试创建文件的md5后缀----------");

        File file = new File("/home/mignet/文档/projects/rustful/test.jpg");

        if(!file.exists()){
            file.createNewFile();
        }
        //获取参数
        String parent = file.getParent();

        System.out.println(parent);
        String fileName = file.getName();
        System.out.println(fileName);
        //首先获取文件的MD5
        String md5 = getFileMD5(file);

        System.out.println("-----获取的md5:" + md5);

        //组装
        File md5File = new File(parent + fileName +".md5");
        if(md5File.exists()){
            md5File.delete();
            md5File.createNewFile();
        }

        FileOutputStream fos = new FileOutputStream(md5File);
        fos.write(md5.getBytes());

        fos.flush();
        fos.close();

        System.out.println("--------完成---------");
    }
}

Rust(好吧,博客园当前还不支持Rust语言,语法高亮是错的,只看红字部分)

//Include macros to be able to use `insert_routes!`.
#[macro_use]
extern crate rustful;
use rustful::{Server, Handler, Context, Response, TreeRouter};

//Test Image And ImageHash
extern crate image;
extern crate crypto;

use crypto::md5::Md5;
use crypto::digest::Digest;

use std::char;
use std::path::Path;
use std::os;
use std::io;
use std::io::prelude::*;
use std::fs::File;
use std::io::BufReader;

use image::GenericImage;

#[macro_use]
extern crate log;
extern crate env_logger;

use std::error::Error;

struct Greeting(&‘static str);

impl Handler for Greeting {
    fn handle_request(&self, context: Context, response: Response) {
        //Check if the client accessed /hello/:name or /good_bye/:name
        if let Some(name) = context.variables.get("name") {
            //Use the value of :name
            response.send(format!("{}, {}", self.0, name));
        } else {
            response.send(self.0);
        }
    }
}
fn main() {
    env_logger::init().unwrap();

    let img = image::open(&Path::new("test.jpg")).unwrap();

    let image2 = image::open(&Path::new("73daacfab6ae5784b9463333f098650b.jpg")).unwrap();

    // The dimensions method returns the images width and height
    println!("dimensions {:?}", img.dimensions());
    let (width, height) = img.dimensions();

    //caculate md5 for file
    let mut f = File::open("/home/mignet/文档/projects/rustful/test.jpg").unwrap();
    let mut buffer = Vec::new();
    // read the whole file
    f.read_to_end(&mut buffer).unwrap();

    let mut hasher = Md5::new();
    hasher.input(&buffer);
    println!("{}", hasher.result_str());

    // The color method returns the image‘s ColorType
    println!("ColorType:{:?}", img.color());

    //Build and run the server.
    let server_result = Server {
        //Turn a port number into an IPV4 host address (0.0.0.0:8080 in this case).
        host: 8080.into(),

        //Create a TreeRouter and fill it with handlers.
        handlers: insert_routes!{
            TreeRouter::new() => {
                //Receive GET requests to /hello and /hello/:name
                "hello" => {
                    Get: Greeting("hello"),
                    ":name" => Get: Greeting("hello")
                },
                //Receive GET requests to /good_bye and /good_bye/:name
                "good_bye" => {
                    Get: Greeting("good bye"),
                    ":name" => Get: Greeting("good bye")
                },
                "/" => {
                    //Handle requests for root...
                    Get: Greeting("Welcome to Rustful!")
                    // ":name" => Get: Greeting("404 not found:")
                }
            }
        },

        //Use default values for everything else.
        ..Server::default()
    }.run();

    match server_result {
        Ok(_server) => {println!("server is running:{}","0.0.0.0:8080");},
        Err(e) => println!("could not start server: {}", e.description())
    }
}
时间: 2024-08-08 09:30:46

计算文件的MD5值(Java & Rust)的相关文章

Linux下C语言计算文件的md5值(32位的)

google了好久都没有找到合适的,其实我只需要一个函数,能计算文件的 md5 值就好, 后来找到了 md5.h 和 md5.c 的源文件,仿照别人的封装了个函数(他那个有问题,和 md5sum 计算出来的都不一样). 废话少说,直接贴代码: (再废一句话,如果只想计算字符串的md5值,把字符串传给 MD5Update 函数一次就好) #include "md5.h" #include <stdio.h> #include <stdlib.h> #include

用Python计算文件的MD5值

尽管计算MD5有很多小工具,重装系统后还得去找,就自己用Python写了一个: getMD5.py import hashlib import sys if __name__ == '__main__': if len(sys.argv)!= 2: sys.exit('argv error!') m = hashlib.md5() n = 1024*4 inp = open(sys.argv[1],'rb') while True: buf = inp.read(n) if buf: m.upd

C# 计算文件的MD5值

/// <summary> /// 计算文件的MD5校验 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static string GetMd5HashFromFile(string fileName) { try { FileStream file = new FileStream(fileNam

python计算文件的md5值

前言 最近要开发一个基于python的合并文件夹/目录的程序,本来的想法是基于修改时间的比较,即判断文件有没有改变,比较两个文件的修改时间即可.这个想法在windows的pc端下测试没有问题. 但是当把一个文件从pc端复制到优盘时出现了一个问题,复制到优盘的文件比pc端的文件慢了两秒钟! 这里我用的复制函数是 shutil.copy2(),理论上它会把修改时间和最后访问时间也复制过来1,但是实际情况并不是完全相同. 详细情况我在segmentfault里提出了问题:为什么将一个文件从pc中复制到

c# 计算字符串和文件的MD5值的方法

快速使用Romanysoft LAB的技术实现 HTML 开发Mac OS App,并销售到苹果应用商店中. <HTML开发Mac OS App 视频教程> 土豆网同步更新:http://www.tudou.com/plcover/VHNh6ZopQ4E/ 百度网盘同步:http://pan.baidu.com/s/1jG1Q58M 分享  [中文纪录片]互联网时代   http://pan.baidu.com/s/1qWkJfcS 官方QQ群:(申请加入,说是我推荐的) App实践出真知 4

计算指定文件的MD5值

原文:计算指定文件的MD5值 /// <summary> /// 计算指定文件的MD5值 /// </summary> /// <param name="fileName">指定文件的完全限定名称</param> /// <returns>返回值的字符串形式</returns> public static String ComputeMD5(String fileName) { var hashMD5 = Stri

C#对文件进行MD5值检测

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.ComponentModel; 7 using System.Data; 8 using System.Drawing; 9 using System.IO; 10 using System.Security.Cryp

在浏览器端获取文件的MD5值

http://www.jianshu.com/p/940a9226fbbd 前几天接到一个奇怪的需求,要在web页面中计算文件的md5值,还好这个项目是只需兼容现代浏览器的,不然要坑死了. 其实对文件进行md5,对于后端来说是及其简单的.比如使用Node.js,只要下面几行代码就可以了: var fs= require('fs'); var crypto = require('crypto'); function md5File(path, callback) { fs.readFile(pat

【转】Java计算文件的hash值

原文地址:http://blog.csdn.net/qq_25646191/article/details/78863110 如何知道一个文件是否改变了呢?当然是用比较文件hash值的方法,文件hash又叫文件签名,文件中哪怕一个bit位被改变了,文件hash就会不同. 比较常用的文件hash算法有MD5和SHA-1.我用的是MD5算法,java中,计算MD5可以用MessageDigest这个类. 下面是代码: [java] view plain copy package com.test;