• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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())
    }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
信号与线性系统分析--Matlab实验报告手册发布时间:2022-07-18
下一篇:
sparse用法matlab官方说明 - 蒲公英的花发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap