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. java如何操作注册表(Preferences类)(在windows的注册表中保存、读取)

    我们经常需要将我们的程序运行中的一些信息(比如在选项对话框中的设置)记录下来,以做便再次运行的时候不用再重写填写这些数据.这对改善软件的人机可用性方面是很有用的.比如:数据库监控.日志工具,JDBMo ...

  2. Uart串口与RS232串口的区别

    Uart指的是TTL电平的串口:RS232指的是RS232电平的串口. TTL电平是3.3V的,而RS232是负逻辑电平,它定义+5~+12V为低电平,而-12~-5V为高电平. Uart串口的RXD ...

  3. uiwebview和 js交互框架

    WebViewJavascriptBridge

  4. kerberos+ladp+hadoop-ha 安全认证部署配置

    随着hadoop集群里的数据量越来越大,各业务数据都集中了里面,自然要为各业务都要提供数据支持,又希望各业务数据是相对独立安全的,这最时候就需要做安全认证了 hadoop ha 测试集群部署规划 ha ...

  5. 用fabric部署维护kle日志收集系统

    最近搞了一个logstash kafka elasticsearch kibana 整合部署的日志收集系统.部署参考lagstash + elasticsearch + kibana 3 + kafk ...

  6. Chapter 6面向对象

    1.Python中预定义的函数在定义的时候有一种很特别的形式,即是函数名是小写,并且函数名前后分别有两个下划线.同样的,在对象中也有预定义的方法,例如所有对象的基类object中的__new__(), ...

  7. swift-基础部分

    变量常量,注释,分号,整数,浮点数.数值行类型转换,类型别名,波尔值,元组,可选,断言              let binaryInteger = 0b10001  let twoThousan ...

  8. YAPF:Google开源的Python代码格式化工具

    点这里 现在的大多数 Python 代码格式化工具(比如:autopep8 和 pep8ify)是可以移除代码中的 lint 错误.这显然有些局限性.比如:遵循 PEP 8 指导的代码可能就不会被格式 ...

  9. C# 获取windows特殊路径

    虽然是古老的问题,最近用到这个,查一下还不少东东呐 一.使用Environment.SpecialFolder 该方法最简单,直接使用即可,只是提供的特殊路径比较少. (1)使用方法:string p ...

  10. js的正则表达式

    正则表达式(regular expression)是一中描述字符模式的对象,js的RegExp类表示正则表达式,String与RegExp都定义了相应的方法来操作正则表达式,比如模式匹配,文本检索和替 ...