计算文件的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 getFileMD5File file){
        String md5 = null;
        FileInputStream fis = null;
        FileChannel fileChannel = null;
        try {
            fis = new FileInputStreamfile);
            fileChannel = fis.getChannel);
            MappedByteBuffer byteBuffer = fileChannel.mapFileChannel.MapMode.READ_ONLY, 0, file.length));
            
            try {
                MessageDigest md = MessageDigest.getInstance"MD5");
                md.updatebyteBuffer);
                md5 = byteArrayToHexStringmd.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 byteArrayToHexStringbyte[] digest) {
        
        StringBuffer buffer = new StringBuffer);
        forint i=0; i<digest.length; i++){
            buffer.appendbyteToHexStringdigest[i]));
        }
        return buffer.toString);
    }
    
    /**
     * 字节转十六进制字符串
     * @param b
     * @return
     */
    private static String byteToHexStringbyte 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 mainString [] 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.printlnparent);
        String fileName = file.getName);
        System.out.printlnfileName);
        //首先获取文件的MD5
        String md5 = getFileMD5file);
        
        System.out.println"-----获取的md5:" + md5);
        
        //组装
        File md5File = new Fileparent + fileName +".md5");
        ifmd5File.exists)){
            md5File.delete);
            md5File.createNewFile);
        }
        
        FileOutputStream fos = new FileOutputStreammd5File);
        fos.writemd5.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 Somename) = context.variables.get"name") {
            //Use the value of :name
            response.sendformat!"{}, {}", self.0, name));
        } else {
            response.sendself.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");},
        Erre) => println!"could not start server: {}", e.description))
    }
}

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注