计算文件的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 ...
随机推荐
- 腾讯开源的轻量级CSS3动画库:JX.Animate
JX.Animate 是由腾讯前端团队 AlloyTeam 推出的一个 CSS3 动画库,通过 JX(腾讯的前端框架)插件的形式提供. Why CSS3 众所周知在支持HTML5的浏览器中 ...
- 微信电脑版也能用公众号自定义菜单 微信1.2 for Windows发布
昨日,微信电脑版发布更新,版本为微信1.2 for Windows,最大的特色就是加入了保存聊天记录功能,可以使用公账号菜单,手机上收藏的表情也能在电脑版上发送,可以接收转账消息. 本次微信pc版更新 ...
- “System.Data.Entity.Internal.AppConfig"的类型初始值设定项引发异常。{转}
<connectionStrings> <add name="ConnectionStringName" providerName="System.Da ...
- 如何修正导入模型的旋转? How do I fix the rotation of an imported model?
原地址:http://game.ceeger.com/Manual/HOWTO-FixZAxisIsUp.html Some 3D art packages export their models s ...
- 报名|「OneAPM x DaoCloud」技术公开课:Docker性能监控!
如今,越来越多的公司开始 Docker 了,「三分之二的公司在尝试了 Docker 后最终使用了它」,也就是说 Docker 的转化率达到了 67%,同时转化时长也控制在 60 天内. 既然 Dock ...
- 如何说服你的老板必须使用APM?
APM研究院 2015/04/24 16:56 2013年,某权威机构提供一组数据显示:亚马逊每100毫秒延迟会使销售额下降1%:雅虎一秒钟服务器延迟导致收入下降2.8%:谷歌搜索结果页面放缓100毫 ...
- 对MySQL DELETE语法的详细解析
以下的文章主要描述的是MySQL DELETE语法的详细解析,首先我们是从单表语法与多表语法的示例开始的,假如你对MySQL DELETE语法的相关内容十分感兴趣的话,你就可以浏览以下的文章对其有个更 ...
- Codeforces Round #336 (Div. 2) B. Hamming Distance Sum 计算答案贡献+前缀和
B. Hamming Distance Sum Genos needs your help. He was asked to solve the following programming pro ...
- HTML CSS——margin与padding的初学
下文引自HTML CSS——margin和padding的学习,作者fengyv,不过加入了一些个人的看法. 你在学习margin和padding的时候是不是懵了,——什么他娘的内边距,什么他娘的外边 ...
- 李洪强iOS开发之- 实现简单的弹窗
李洪强iOS开发之- 实现简单的弹窗 实现的效果: 112222222222223333333333333333