Get the MD5 value of the file

public   void getMd5OfFile() { 
      // This is the file stream obtained from mongodb //DBObject dbObject
= new BasicDBObject("filename","yansebuyiyangdeyanhuo5"); // DB db = mongoTemplate.getDb (); //GridFS fs = new GridFS(db,"myfiles"); //GridFSDBFile gridFSDBFile = fs.findOne(dbObject); //InputStream in = gridFSDBFile.getInputStream();
     String filePath = "文件路径";
     InputStream is = null;
     try{   in = new FileInputStram(new File(filePath));
MessageDigest messageDigest = MessageDigest.getInstance("MD5"); byte[] bytes = new byte[1024]; int byteCount = 0; while ((byteCount = in.read(bytes)) !=-1) { messageDigest.update(bytes, 0, byteCount); } byte[] digest = messageDigest.digest(); // byte -128 ---- 127 StringBuffer sb = new StringBuffer(); for (byte b : digest) { int a = b & 0xff; // Log.d(TAG, "" + a); String hex = Integer.toHexString(a); if (hex.length() == 1) { hex = 0 + hex; } sb.append(hex); } System.err.println( "MD5 value: ================================="+sb.toString() ); }catch(Exception e) { e.printStackTrace (); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace (); } in = null; } } }
//Get the md5 value of the string
public void getMd5ofString( ){ String text = "AABJRU5ErkJggg=="; try { MessageDigest messageDigest = MessageDigest.getInstance("md5"); byte[] buffer = messageDigest.digest(text.getBytes()); // byte -128 ---- 127 StringBuffer sb = new StringBuffer(); for (byte b : buffer) { int a = b & 0xff; String hex = Integer.toHexString(a); if (hex.length() == 1) { hex = 0 + hex; } sb.append(hex); } System.err.println( "MD5 value: ================================="+ sb.toString() ); } catch (NoSuchAlgorithmException e) { } }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324668259&siteId=291194637