Calculate the MD5 value of a file (Java & Rust)

Source: Internet
Author: User

Java

 Public classTestFileMD5 { Public Final StaticString[] hexdigits = {"0", "1", "2", "3", "4", "5",        "6", "7", "8", "9", "a", "B", "C", "D", "E", "F" }; /*** Get the MD5 value of the file *@paramfile *@return     */     Public Staticstring getFileMD5 (file file) {string MD5=NULL; FileInputStream FIS=NULL; FileChannel FileChannel=NULL; Try{FIS=Newfileinputstream (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 (); }        }                returnMD5; }        /*** byte array to hexadecimal string *@paramDigest *@return     */    Private StaticString bytearraytohexstring (byte[] Digest) {StringBuffer buffer=NewStringBuffer ();  for(inti=0; i<digest.length; i++) {buffer.append (bytetohexstring (digest[i)); }        returnbuffer.tostring (); }        /*** Byte to hexadecimal string *@paramb *@return     */    Private StaticString bytetohexstring (byteb) {//int d1 = N/16;             intD1 = (b&0xf0) >>4; //int d2 = n%16;             intD2 = b&0xf; returnHEXDIGITS[D1] +HEXDIGITS[D2]; }         Public Static voidMain (String [] args)throwsexception{System.out.println ("-----The MD5 suffix of the created file----------"); File File=NewFile ("/home/mignet/document/projects/rustful/test.jpg"); if(!file.exists ())        {File.createnewfile (); }        //Get ParametersString parent =file.getparent ();        SYSTEM.OUT.PRINTLN (parent); String FileName=File.getname ();        System.out.println (FileName); //first get the MD5 of the fileString MD5 =getFileMD5 (file); SYSTEM.OUT.PRINTLN ("-----Gets the MD5:" +MD5); //AssemblyFile Md5file =NewFile (parent + FileName + ". MD5"); if(Md5file.exists ()) {md5file.delete ();        Md5file.createnewfile (); } FileOutputStream Fos=NewFileOutputStream (Md5file);                Fos.write (Md5.getbytes ());        Fos.flush ();                Fos.close (); System.out.println ("--------Complete---------"); }}

Rust (well, the blog Park does not currently support the Rust language, syntax highlighting is wrong, just look at the Scarlet Letter part)

//Include macros to is 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::d igest::D igest; Use Std::char;use std::p ath::P ath;use std::os;use std::io;use std::io::p relude::*; 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 forGreeting {fn Handle_request (&Self , context:context, Response:response) {        CheckifThe client Accessed/hello/:nameor/good_bye/: NameifLet 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 andHeight println! ("dimensions {:?}", Img.dimensions ()); Let (width, height)=img.dimensions (); //caculate MD5 for file let mut f = File::open ("/home/mignet/document/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 ColorTypeprintln! ("colortype:{:?}", Img.color ()); Build andrun the server. Let Server_result=Server {Turn a port number into an IPV4 host address (0.0.0.0:8080inchThis case ). Host:8080. into (),Create a Treerouter andfill 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 forroot ... Get:greeting ("Welcome to rustful!")                    //": Name"= Get:greeting ("404 Not Found:")                }            }        },        Use default values forEverythingElse. ..    Server::d efault ()}.run (); Match Server_result {Ok (_server)= = {println! ("server is running:{}","0.0.0.0:8080");}, ERR (e)= println! ("could not start server: {}", E.description ())}}

Calculate the MD5 value of a file (Java & Rust)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.