計算檔案的MD5值(Java & Rust)

來源:互聯網
上載者:User

標籤:

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 ImageHashextern 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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.