计算文件的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 ...
随机推荐
- NYOJ-214 单调递增子序列(二) AC 分类: NYOJ 2014-01-31 08:06 233人阅读 评论(0) 收藏
#include<stdio.h> #include<string.h> int len, n, i, j; int d[100005], a[100005]; int bin ...
- 【转载】c/c++在windows下获取时间和计算时间差的几种方法总结
一.标准C和C++都可用 1.获取时间用time_t time( time_t * timer ),计算时间差使用double difftime( time_t timer1, time_t time ...
- unset之讲解
unset (PHP 4, PHP 5) unset — 释放给定的变量 说明¶ void unset ( mixed $var [, mixed $... ] ) unset() 销毁指定的变量. ...
- ObjC的Block中使用weakSelf/strongSelf @weakify/@strongify
首先要说说什么时候使用weakSelf和strongSelf. 下面引用一篇博客<到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf>的内容: Objec ...
- HDOJ 2181 哈密顿绕行世界问题
哈密顿绕行世界问题 Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total S ...
- linux下命令行查看Memcached运行状态(shell)
stats查看memcached状态的基本命令,通过这个命令可以看到如下信息:STAT pid 22459 进程IDSTAT uptime 10 ...
- POJ 1151 Atlantis(经典的线段树扫描线,求矩阵面积并)
求矩阵的面积并 采用的是区间更新 #include <iostream> #include <stdio.h> #include <string.h> #inclu ...
- hdu 4768 Flyer 二分
思路:由于最多只有一个是奇数,所以二分枚举这个点,每次判断这个点的左边区间段所有点的和作为 二分的依据. 代码如下: #include<iostream> #include<cstd ...
- LINUX输入输出与文件
1 文件描述符 内核为每个进程维护一个已打开文件的记录表(实现为结构体数组),文件描述符是一个较小的正整数(0-1023)(结构体数组下标),它代表记录表的一项,通过文件描述符和一组基于文件描述符的文 ...
- poj 1797(最短路变形)
题目链接:http://poj.org/problem?id=1797 思路:题目意思很简单,n个顶点,m条路,每条路上都有最大载重限制,问1->n最大载重量.其实就是一最短路的变形,定义wei ...