计算文件的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 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)的更多相关文章
- C#计算文件的MD5值实例
C#计算文件的MD5值实例 MD5 是 Message Digest Algorithm 5(信息摘要算法)的缩写,MD5 一种散列(Hash)技术,广泛用于加密.解密.数据签名和数据完整性校验等方面 ...
- c#计算文件的MD5值
代码: /// <summary> /// 计算文件的 MD5 值 /// </summary> /// <param name="fileName" ...
- 计算文件的MD5值和sha256值
1.计算文件的MD5值. 1)linux系统计算 MD5值:md5sum+文件名 sha256值:sha256su+文件名 2)windows系统计算 MD5值:利用Notepad++工具计算 sha ...
- 在.NET中计算文件的MD5值
更新记录 本文迁移自Panda666原博客,原发布时间:2021年7月2日. 直接上代码吧: using System; using System.IO; using System.Security. ...
- python计算文件的md5值
前言 最近要开发一个基于python的合并文件夹/目录的程序,本来的想法是基于修改时间的比较,即判断文件有没有改变,比较两个文件的修改时间即可.这个想法在windows的pc端下测试没有问题. 但是当 ...
- 计算字符串和文件的MD5值
//计算字符串的MD5值 public string GetMD5(string sDataIn) { MD5CryptoServiceProvider md5 = new MD5CryptoServ ...
- 计算指定文件的MD5值
/// <summary> /// 计算指定文件的MD5值 /// </summary> /// <param name="fileName"> ...
- c# 计算字符串和文件的MD5值的方法
快速使用Romanysoft LAB的技术实现 HTML 开发Mac OS App,并销售到苹果应用商店中. <HTML开发Mac OS App 视频教程> 土豆网同步更新:http: ...
- C# 计算文件的 Hash 值
/// <summary> /// 提供用于计算指定文件哈希值的方法 /// <example>例如计算文件的MD5值: /// <code> /// String ...
随机推荐
- win7 IIS7 PHP环境配置
PHP5.2.17 官方下载: http://windows.php.net/downloads/releases/php-5.2.17-Win32-VC6-x86.zip PHP5.3.5 官方下载 ...
- bootstrap学习记录(慕课网教程)
1.当主标题下需要副标题时可在h中嵌套small<h1>nihao<small>a</samll></h1> 2.当某一段落需要突出显示时可添加lead ...
- Codeforces Round #261 (Div. 2)
第一场难得DIV2简单+AK人数多: E:给出一张图,求最多的边数,满足:在这个边的集合中后面的边的权值大于前面的边; 思路:我们将图按权值排列,以为只可能边权值小的跟新权值大的所以对于一条边我们只跟 ...
- POJ 1547
#include<iostream> #include<string> using namespace std; int main() { int length; int hi ...
- Nginx状态监控
通过配置nginx.conf文件来实现对Nginx状态信息的监控. 1.配置nginx.conf vim /usr/local/nginx/conf/nginx.conf 再server块配置项中添加 ...
- mysql 连接数的最大数
mysql默认最大连接数是100,增加加默认MYSQL连接数的方法有两个 方法一:进入MYSQL安装目录 打开MYSQL配置文件 my.ini(windows) 或 my.cnf(linux环境)查找 ...
- MongoDB (一) MongoDB 介绍
MongoDB 是一个跨平台的,面向文档的数据库,提供高性能,高可用性和可扩展性方便. MongoDB工作在收集和文件的概念. 数据库 数据库是一个物理容器集合.每个数据库都有自己的一套文件系统上的文 ...
- apache 的ab 工具
ab是apache 进行http服务器压力测试的一个工具.用来衡量apache 服务器的执行效率,能够检测出apache每秒能够处理的请求数. 一个使用的例子如下(windows下) ab -n -c ...
- MyBatis学习总结_10_批量操作
一.mybatis中的批量操作 批量操作核心就是一次传入多个数据然后进行相关操作,增删改查中掌握其中一个其他的也不成问题 1.最新在做的短信平台,要批量插入群发的短信记录: 当然批量操作还有:批 ...
- 在CentOS下面编译WizNote Qt Project
编译环境 CentOS 64位 Desktop 版本:6.5 编译前的准备: CentOS的用户默认没有root权限,如果当前用户没有权限root,则可以在终端里面执行下面的命令: su root s ...