Print md5 checksum values using hashmap and strings

i have following code for comparing the md5 hash values for two folder but i need to show the list of files and the hash value of each file. can anyone please help me out with this. i just need to get hash value for one folder only.

package com.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class Compare 
{
//This can be any folder locations which you want to compare
File dir1 = new File("/Users/Samip/Desktop/crypto");
File dir2 = new File("/Users/Samip/Desktop/crypto1");
public static void main(String ...args) 
{
    Compare compare = new Compare();
    try
    {
        compare.getDiff(compare.dir1,compare.dir2);
    }
    catch(IOException ie)
    {
        ie.printStackTrace();
    }
}

public void getDiff(File dirA, File dirB) throws IOException
{
    File[] fileList1 = dirA.listFiles();
    File[] fileList2 = dirB.listFiles();
    Arrays.sort(fileList1);
    Arrays.sort(fileList2);
    HashMap<String, File> map1;
    if(fileList1.length < fileList2.length)
    {
        map1 = new HashMap<String, File>();
        for(int i=0;i<fileList1.length;i++)
        {
            map1.put(fileList1[i].getName(),fileList1[i]);
        }

        compareNow(fileList2, map1);
    }
    else
    {
        map1 = new HashMap<String, File>();
        for(int i=0;i<fileList2.length;i++)
        {
            map1.put(fileList2[i].getName(),fileList2[i]);
        }
        compareNow(fileList1, map1);
    }
}

public void compareNow(File[] fileArr, HashMap<String, File> map) throws IOException
{
    for(int i=0;i<fileArr.length;i++)
    {
        String fName = fileArr[i].getName();
        File fComp = map.get(fName);
        map.remove(fName);
        if(fComp!=null)
        {
            if(fComp.isDirectory())
            {
                getDiff(fileArr[i], fComp);
            }
            else
            {
                String cSum1 = checksum(fileArr[i]);
                String cSum2 = checksum(fComp);
                if(!cSum1.equals(cSum2))
                {
                    System.out.println(fileArr[i].getName()+"\t\t"+ "different");
                }
                else
                {
                    System.out.println(fileArr[i].getName()+"\t\t"+"identical");
                }
            }
        }
        else
        {
            if(fileArr[i].isDirectory())
            {
                traverseDirectory(fileArr[i]);
            }
            else
            {
                System.out.println(fileArr[i].getName()+"\t\t"+"only in "+fileArr[i].getParent());
            }
        }
    }
    Set<String> set = map.keySet();
    Iterator<String> it = set.iterator();
    while(it.hasNext())
    {
        String n = it.next();
        File fileFrmMap = map.get(n);
        map.remove(n);
        if(fileFrmMap.isDirectory())
        {
            traverseDirectory(fileFrmMap);
        }
        else
        {
            System.out.println(fileFrmMap.getName() +"\t\t"+"only in "+ fileFrmMap.getParent());
        }
    }
}

public void traverseDirectory(File dir)
{
    File[] list = dir.listFiles();
    for(int k=0;k<list.length;k++)
    {
        if(list[k].isDirectory())
        {
            traverseDirectory(list[k]);
        }
        else
        {
            System.out.println(list[k].getName() +"\t\t"+"only in "+ list[k].getParent());
        }
    }
}

public String checksum(File file) 
{
    try 
    {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do 
        {
            read = fin.read(buffer);
            if (read > 0)
                md5er.update(buffer, 0, read);
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null)
          return null;
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) 
        {
            strDigest += Integer.toString((digest[i] & 0xff) + 0x100,    16).substring(1).toUpperCase();
        }
        return strDigest;
    } 
    catch (Exception e) 
    {
        return null;
    }
}
 }

Answers


In you main method, instead using Compare.getDiff(dir1, dir2) you want to

  1. Get a file listing of your target directory
  2. Invoke Compare.checksum(file) on each file and print the result

Looks like you have all the code, you just need to reshape it a little.


Consider this example. The hash-generating code has been taken from your previous question - same goes for the file-iteration code. You just replace that folder to match your.

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

public class PrintChecksums {

    public static void main(String[] args) {
        String sourceDir = "/Users/Jan/Desktop/Folder1";
        try {
            new PrintChecksums().printHashs(new File(sourceDir));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void printHashs(File sourceDir) throws Exception {
        for (File f : sourceDir.listFiles()) {
            String hash = createHash(f); // That you almost have
            System.out.println(f.getAbsolutePath() + " / Hashvalue: " + hash);
        }
    }

    public String createHash(File datafile) throws Exception {
        // SNIP - YOUR CODE BEGINS
        MessageDigest md = MessageDigest.getInstance("SHA1");
        FileInputStream fis = new FileInputStream(datafile);
        byte[] dataBytes = new byte[1024];

        int nread = 0;

        while ((nread = fis.read(dataBytes)) != -1) {
            md.update(dataBytes, 0, nread);
        }

        byte[] mdbytes = md.digest();

        // convert the byte to hex format
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < mdbytes.length; i++) {
            sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        // SNAP - YOUR CODE ENDS
        return sb.toString();
    }

}

Please have a look at the below code. I have added a function printCheckSum() which iterates though directory, scans each file and prints its hash value.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class Compare 
{
//This can be any folder locations which you want to compare
File dir1 = new File("D:\\dir1");
File dir2 = new File("D:\\dir2");
public static void main(String ...args) 
{
    Compare compare = new Compare();
    try
    {
        compare.printCheckSum(compare.dir1);
    }
    catch(IOException ie)
    {
        ie.printStackTrace();
    }
}

public void getDiff(File dirA, File dirB) throws IOException
{
    File[] fileList1 = dirA.listFiles();
    File[] fileList2 = dirB.listFiles();
    Arrays.sort(fileList1);
    Arrays.sort(fileList2);
    HashMap<String, File> map1;
    if(fileList1.length < fileList2.length)
    {
        map1 = new HashMap<String, File>();
        for(int i=0;i<fileList1.length;i++)
        {
            map1.put(fileList1[i].getName(),fileList1[i]);
        }

        compareNow(fileList2, map1);
    }
    else
    {
        map1 = new HashMap<String, File>();
        for(int i=0;i<fileList2.length;i++)
        {
            map1.put(fileList2[i].getName(),fileList2[i]);
        }
        compareNow(fileList1, map1);
    }
}

public void compareNow(File[] fileArr, HashMap<String, File> map) throws IOException
{
    for(int i=0;i<fileArr.length;i++)
    {
        String fName = fileArr[i].getName();
        File fComp = map.get(fName);
        map.remove(fName);
        if(fComp!=null)
        {
            if(fComp.isDirectory())
            {
                getDiff(fileArr[i], fComp);
            }
            else
            {
                String cSum1 = checksum(fileArr[i]);
                String cSum2 = checksum(fComp);
                if(!cSum1.equals(cSum2))
                {
                    System.out.println(fileArr[i].getName()+"\t\t"+ "different");
                }
                else
                {
                    System.out.println(fileArr[i].getName()+"\t\t"+"identical");
                }
            }
        }
        else
        {
            if(fileArr[i].isDirectory())
            {
                traverseDirectory(fileArr[i]);
            }
            else
            {
                System.out.println(fileArr[i].getName()+"\t\t"+"only in "+fileArr[i].getParent());
            }
        }
    }
    Set<String> set = map.keySet();
    Iterator<String> it = set.iterator();
    while(it.hasNext())
    {
        String n = it.next();
        File fileFrmMap = map.get(n);
        map.remove(n);
        if(fileFrmMap.isDirectory())
        {
            traverseDirectory(fileFrmMap);
        }
        else
        {
            System.out.println(fileFrmMap.getName() +"\t\t"+"only in "+ fileFrmMap.getParent());
        }
    }
}

public void traverseDirectory(File dir)
{
    File[] list = dir.listFiles();
    for(int k=0;k<list.length;k++)
    {
        if(list[k].isDirectory())
        {
            traverseDirectory(list[k]);
        }
        else
        {
            System.out.println(list[k].getName() +"\t\t"+"only in "+ list[k].getParent());
        }
    }
}

public String checksum(File file) 
{
    try 
    {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do 
        {
            read = fin.read(buffer);
            if (read > 0)
                md5er.update(buffer, 0, read);
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null)
          return null;
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) 
        {
            strDigest += Integer.toString((digest[i] & 0xff) + 0x100,    16).substring(1).toUpperCase();
        }
        return strDigest;
    } 
    catch (Exception e) 
    {
        return null;
    }
}

public void printCheckSum(File dir) throws IOException{

     File[] fileList = dir.listFiles();

     for(File file : fileList){

         if(file.isDirectory()){
             printCheckSum(file);

         }else
              System.out.println(file.getName() +"\t :: \t" + checksum(file));
     }

}
 }

Hope this helps. Cheers!


Need Your Help

hide and show divs using javascript

javascript

I have multiple links in a page. When I click a particular link I want a div which contains the details of that link and hide all other divs associated with other link in the same page

Store XML data in Core Data

iphone objective-c core-data

is there any easy way of store XML data into core data?