FileKit.java

 

Download FileKit.java source file

// FileKit is intended to be a collection of generally useful methods
// for working with files.  All it does now is MD5 digests on files.
// A test driver (main) is included to test the various methods.  Usage:
//    java FileKit filename
// (todo: add GUI File selection interface.)
//
// Written 10/2002 by Wayne Pollock, Tampa FL USA.  All Rights Reserved.

// package com.wpollock.utils;

import java.io.*;
import java.security.*;

public class FileKit
{
   // A lookup is more efficient than using Integer.toHexDigit():
   private static final char [] hexDigit =
      { '0', '1', '2', '3', '4', '5', '6', '7',
        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

   public static String md5Digest ( String filename ) throws IOException
   {  return md5Digest( new FileInputStream( filename ) );  }

   public static String md5Digest ( File file ) throws IOException
   {  return md5Digest( new FileInputStream( file ) );  }

   public static String md5Digest ( FileInputStream fis ) throws IOException
   {
      byte [] buffer = new byte[1024];
      MessageDigest md = null;

      try
      {   md = MessageDigest.getInstance( "MD5" );
      } catch ( NoSuchAlgorithmException nsae )
      {   System.out.println( nsae ); System.exit( 1 );  }

      for ( ; ; )  // Do forever
      {  int numOfBytesRead = fis.read( buffer );
         if ( numOfBytesRead < 1 )
            break;
         md.update( buffer, 0, numOfBytesRead );
      }
      fis.close();
      return hexString( md.digest() );
   }

   private static String hexString ( byte [] bytes )
   {
      // Converts an array of bytes to a String of hex digits,
      // with a space between groups of four digits.
      // Note that the MD5 digest is always 128 bits = 16 bytes,
      // so there will be 5 * 16 / 2 = 40 (32 hex digits plus
      // 7 spaces = 39 characters, which is close enough).

      StringBuffer s = new StringBuffer( 5 * bytes.length / 2 );

      for ( int i = 0; i < bytes.length; ++i )
      {  int d1 = ( bytes[i] & 0x0000000F );
         int d2 = ( bytes[i] & 0x000000F0 ) >>> 4;

         // Output a space seperator after every 4th hex digit:
         if ( i % 2 == 0 && i != 0 )
            s.append( ' ' );

         s.append( hexDigit[d2] );
         s.append( hexDigit[d1] );
      }

      return s.toString();
   }

   // Test driver for md5
   public static void main ( String [] args ) throws Exception
   {
      if ( args.length == 0 )
      {  System.out.println( "Usage: java FileKit filename" );
         System.out.println( "       will display the MD5 digest "
             + "(or \"fingerprint\") for the named file." );
         System.exit( 0 );
      }

      System.out.println( "File:       " + args[0] );
      System.out.println( "MD5 Digest: " + md5Digest( args[0] ) );
   }
}