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

Posted MapReduce Raft /Java Go Rust

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算文件的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 images 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())
    }
}

 

以上是关于计算文件的MD5值(Java & Rust)的主要内容,如果未能解决你的问题,请参考以下文章

Java计算文件MD5值代码

java 获取1G文件md5 要多久

linuxshell怎么计算设备文件的md5

shell脚本获取MD5值

java计算MD5值

计算指定文件的MD5值