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

   2023-02-09 学习力0
核心提示:Javapublic class TestFileMD5 {public final static String[] hexDigits = { "0", "1", "2", "3", "4", "5","6", "7", "8", "9", "a", "b", &qu

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举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • bloom-server 基于 rust 编写的 rest api cache 中间件
    bloom-server 基于 rust 编写的 rest api cache
    bloom-server 基于 rust 编写的 rest api cache 中间件,他位于lb 与api worker 之间,使用redis 作为缓存内容存储, 我们需要做的就是配置proxy,同时他使用基于share 的概念,进行cache 的分布存储,包含了请求端口(proxy,访问数据) 以及cache 控制端口(
    03-08
  • #新闻拍一拍# Oracle 调研如何避免让 Java 开发者投奔 Rust 和 Kotlin | Linux 中国
    #新闻拍一拍# Oracle 调研如何避免让 Java 开发
     导读:• 英特尔对迟迟不被 Linux 主线接受的 SGX Enclave 进行了第 38 次修订 • ARM 支持开源的 Panfrost Gallium3D 驱动本文字数:977,阅读时长大约:1分钟作者:硬核老王Oracle 调研如何避免让 Java 开发者投奔 Rust 和 KotlinOracle 委托分析公司 Omd
    03-08
  • Linux系统下Rust快速安装:国内镜像加速
    Linux系统下Rust快速安装:国内镜像加速
    官方网址和方法Install Rust - Rust Programming Language然而速度慢得让人难以置信。利用国内镜像进行windows的Linux子系统的Rust安装。rust 使用国内镜像,快速安装方法参考:RUST安装慢怎么办,使用镜像方式安装_网络_为中华之崛起而编程-CSDN博客我的操作
    03-08
  • Rust到底值不值得学--Rust对比、特色和理念
    前言其实我一直弄不明白一点,那就是计算机技术的发展,是让这个世界变得简单了,还是变得更复杂了。当然这只是一个玩笑,可别把这个问题当真。然而对于IT从业者来说,这可不是一个玩笑。几乎每一次的技术发展,都让这个生态变得更为复杂。“英年早秃”已经成
    03-08
  • 超33000行新代码,为Linux内核添加Rust支持的补丁已准备就绪
    超33000行新代码,为Linux内核添加Rust支持的补
    https://mp.weixin.qq.com/s/oKw9aBJSdmRoO6-rbLAkNw7 月 4 日,一套修订后的补丁被提交至 Linux 内核的邮件列表中,该补丁为在 Linux 内核中以 Rust 作为辅助编程语言提供了支持,借助 Rust 可以提高 Linux 内核和内存的安全。整套补丁包含 17 个子项,不光
    03-08
  • 【译】Rust 的 Result 类型入门
    【译】Rust 的 Result 类型入门
    A Primer on Rust’s Result Type 译文原文链接:https://medium.com/@JoeKreydt/a-primer-on-rusts-result-type-66363cf18e6a原文作者:Joe Kreydt译文出处:https://github.com/suhanyujie/article-transfer-rs译者:suhanyujietips:水平有限,翻译不当之
    03-08
  • Rust实战系列-基本语法
    Rust实战系列-基本语法
    主要介绍 Rust 的语法、基本类型和数据结构,通过实现一个简单版 grep 命令行工具,来理解 Rust 独有的特性。本文是《Rust in action》学习总结系列的第二部分,更多内容请看已发布文章:一、Rust实战系列-Rust介绍“主要介绍 Rust 的语法、基本类型和数据结
    03-08
  • 全栈程序员的新玩具Rust(三)板条箱
    上次用到了stdout,这次我们来写一个更复杂一点的游戏rust的标准库叫做std,默认就会引入。这次我们要用到一个随机数函数,而随机数比较尴尬的一点是这玩意不在标准库中,我们要额外依赖一个库。很多编程方案都有自己的模块化库系统,rust也不例外,不过rust
    02-10
  • 全栈程序员的新玩具Rust(六)第一个WASM程序
    全栈程序员的新玩具Rust(六)第一个WASM程序
    先上代码https://gitee.com/lightsever/rust_study/tree/master/wasm_hello01webassembly就不用再赘述了,耳朵里面快磨出茧子来了。rustwasm是火狐自家的玩具,让我们来继续做实验,让rust飞起来吧。环境安装安装好rust环境之后仍然需要 一个 wasm 工具包carg
    02-10
  • 【Rust】标准库-Result rust数据库
    环境Rust 1.56.1VSCode 1.61.2概念参考:https://doc.rust-lang.org/stable/rust-by-example/std/result.html示例main.rsmod checked {#[derive(Debug)]pub enum MathError {DivisionByZero,NonPositiveLogarithm,NegativeSquareRoot,}pub type MathResult =
    02-09
点击排行