[Java] Java 对文件进行 CRC32 校验 →→→→→进入此内容的聊天室

来自 , 2020-10-08, 写在 Java, 查看 111 次.
URL http://www.code666.cn/view/1e48c442
  1. import java.util.zip.CheckedInputStream;
  2. import java.util.zip.CRC32;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7.  
  8. /**
  9.  * -----------------------------------------------------------------------------
  10.  * Used to provide an example of how to calculate the checksum of a file using
  11.  * the CRC-32 checksum engine.
  12.  *
  13.  * @version 1.0
  14.  * @author  Jeffrey M. Hunter  (jhunter@idevelopment.info)
  15.  * @author  <a href="http://www.idevelopment.info">http://www.idevelopment.info
  16.  * -----------------------------------------------------------------------------
  17.  */
  18.  
  19. public class ChecksumCRC32 {
  20.  
  21.     private static void doChecksum(String fileName) {
  22.  
  23.         try {
  24.  
  25.             CheckedInputStream cis = null;
  26.             long fileSize = 0;
  27.             try {
  28.                 // Computer CRC32 checksum
  29.                 cis = new CheckedInputStream(
  30.                         new FileInputStream(fileName), new CRC32());
  31.  
  32.                 fileSize = new File(fileName).length();
  33.  
  34.             } catch (FileNotFoundException e) {
  35.                 System.err.println("File not found.");
  36.                 System.exit(1);
  37.             }
  38.  
  39.             byte[] buf = new byte[128];
  40.             while(cis.read(buf) >= 0) {
  41.             }
  42.  
  43.             long checksum = cis.getChecksum().getValue();
  44.             System.out.println(checksum + " " + fileSize + " " + fileName);
  45.  
  46.         } catch (IOException e) {
  47.             e.printStackTrace();
  48.             System.exit(1);
  49.         }
  50.  
  51.     }
  52.  
  53.     /**
  54.      * Sole entry point to the class and application.
  55.      * @param args Array of String arguments.
  56.      */
  57.     public static void main(String[] args) {
  58.  
  59.         if (args.length != 1) {
  60.             System.err.println("Usage: java ChecksumCRC32 filename");
  61.         } else {
  62.             doChecksum(args[0]);
  63.         }
  64.  
  65.     }
  66.  
  67. }
  68. //该片段来自于http://yuncode.net
  69.  

回复 "Java 对文件进行 CRC32 校验"

这儿你可以回复上面这条便签

captcha