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

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

  1. C#计算文件的MD5值实例

    C#计算文件的MD5值实例 MD5 是 Message Digest Algorithm 5(信息摘要算法)的缩写,MD5 一种散列(Hash)技术,广泛用于加密.解密.数据签名和数据完整性校验等方面 ...

  2. c#计算文件的MD5值

    代码: /// <summary> /// 计算文件的 MD5 值 /// </summary> /// <param name="fileName" ...

  3. 计算文件的MD5值和sha256值

    1.计算文件的MD5值. 1)linux系统计算 MD5值:md5sum+文件名 sha256值:sha256su+文件名 2)windows系统计算 MD5值:利用Notepad++工具计算 sha ...

  4. 在.NET中计算文件的MD5值

    更新记录 本文迁移自Panda666原博客,原发布时间:2021年7月2日. 直接上代码吧: using System; using System.IO; using System.Security. ...

  5. python计算文件的md5值

    前言 最近要开发一个基于python的合并文件夹/目录的程序,本来的想法是基于修改时间的比较,即判断文件有没有改变,比较两个文件的修改时间即可.这个想法在windows的pc端下测试没有问题. 但是当 ...

  6. 计算字符串和文件的MD5值

    //计算字符串的MD5值 public string GetMD5(string sDataIn) { MD5CryptoServiceProvider md5 = new MD5CryptoServ ...

  7. 计算指定文件的MD5值

    /// <summary> /// 计算指定文件的MD5值 /// </summary> /// <param name="fileName"> ...

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

    快速使用Romanysoft LAB的技术实现 HTML 开发Mac OS App,并销售到苹果应用商店中.   <HTML开发Mac OS App 视频教程> 土豆网同步更新:http: ...

  9. C# 计算文件的 Hash 值

    /// <summary> /// 提供用于计算指定文件哈希值的方法 /// <example>例如计算文件的MD5值: /// <code> /// String ...

随机推荐

  1. Leetcode#106 Construct Binary Tree from Inorder and Postorder Traversal

    原题地址 二叉树基本操作 [       ]O[              ] [       ][              ]O 代码: TreeNode *restore(vector<i ...

  2. if in hlsl

    seems that in HLSL_4, we can use if https://msdn.microsoft.com/en-us/library/bb313972(v=xnagamestudi ...

  3. Swift-6-函数

    // Playground - noun: a place where people can play import UIKit // 定义和调用函数 func sayHello(personName ...

  4. HDU 1104 Remainder

    与前一题类似,也是BFS+记录路径, 但是有很多BUG点, 第一MOD操作与%不同i,其实我做的时候注意到了我们可以这样做(N%K+K)%K就可以化为正数,但是有一点要注意 N%K%M!=N%M%K; ...

  5. SWF Web播放器

    <HTML> <HEAD> <!-- saved from url=(0013)about:internet --> <TITLE> Untitled. ...

  6. 在iptables防火墙下开启vsftpd的端口

    在开启vsftpd端口后发现用客户端工具能登陆,但无法浏览文件和新建文件.此时看了一下ftp的协议,发现ftp有主动模式和被动模式.在服务端开21端口是让客户端进来,并没有出去的端口,还在服务端开启出 ...

  7. Cortex-M3/4的Hard Fault调试方法

    1 Cortex-M3/4的Fault简介 Cortex-M3/4的Fault异常是由于非法的存储器访问(比如访问0地址.写只读存储位置等)和非法的程序行为(比如除以0等)等造成的.常见的4种异常及产 ...

  8. Mobile Web 调试指南(2):远程调试

    原文:http://blog.jobbole.com/68606/ 原文出处: 阿伦孟的博客(@allenm ) 第一篇中讲解了如何让手机来请求我们开发电脑上的源码,做到了这步后,我们可以改完代码立即 ...

  9. linux权威指南 简记

    /proc 目录,linxu系统以文件形式存放进程信息,这是一个虚拟的文件系统,不占有任何磁盘空间,当读取该文件系统时,系统内核会拦截动作,并动态产生文件与目录的内容 查看该文件夹,会发现很多已数字命 ...

  10. poj 2068 Nim 博弈论

    思路:dp[i][j]:第i个人时还剩j个石头. 当j为0时,有必胜为1: 后继中有必败态的为必胜态!!记忆化搜索下就可以了! 代码如下: #include<iostream> #incl ...