Java:基于MD5的文件监听程序

前述和需求说明

  和之前写的 Python:基于MD5的文件监听程序 是同样的功能,就不啰嗦了,就是又写了一个java版本的,可以移步 python 版本去看一下,整个的核心思路是一样的。代码已上传Github

 

类说明

  FileMd5.java 利用md5生成文件hash值
  fileWalk.java 只是一个文件遍历的demo,没有被其他类调用
  myFileListener.java 主程序,监控文件夹,用到了文件遍历,调用了FileMd5中的FileMd5类

 

代码

FileMd5.java

 1 package myFileListener;
 2 
 3 import java.security.DigestInputStream;
 4 import java.security.MessageDigest;
 5 import java.security.NoSuchAlgorithmException;
 6 import java.io.FileInputStream;
 7 import java.io.IOException;
 8 
 9 public class FileMd5 {
10     public static String fileMd5(String inputFile) throws IOException{
11         
12         int bufferSize = 1024*1024;  //缓冲区大小
13         FileInputStream fileInputStream = null;
14         DigestInputStream digestInputStream = null;
15         
16         try {
17             //获取MD5的实例
18             MessageDigest messageDigest = MessageDigest.getInstance("MD5");
19             
20             fileInputStream = new FileInputStream(inputFile);
21             
22             digestInputStream = new DigestInputStream(fileInputStream, messageDigest);   //Creates a digest input stream, using the specified input stream and message digest.
23             
24             byte[] buffer = new byte[bufferSize];   //设置缓冲区,辅助读取文件,避免文件过大,导致的IO开销
25             while(digestInputStream.read(buffer)>0);  //read: updates the message digest    return int
26             // 获取最终的MessageDigest
27             messageDigest = digestInputStream.getMessageDigest();
28             // 拿到结果 return字节数组byte[] 包含16个元素
29             byte[] resultByteArray = messageDigest.digest();
30             
31             return byteArrayToHex(resultByteArray);       //转换byte 为 string 类型
32             
33         }catch(NoSuchAlgorithmException e) {
34             return null;
35         }finally {
36             try {
37                 digestInputStream.close();
38                 fileInputStream.close();
39             }catch (Exception e) {
40                 System.out.println(e);
41             }
42         }
43     }
44     
45     public static String byteArrayToHex(byte[] byteArray){
46         char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
47         //一个字节是八位二进制 也就是2位十六进制字符
48         char[] resultCharArray = new char[byteArray.length*2];
49 
50         int index = 0;
51         for(byte b : byteArray){
52             resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];
53             resultCharArray[index++] = hexDigits[b& 0xf];
54         }
55         return new String(resultCharArray);
56     }
57 }

 

myFileListener.java

  1 package myFileListener;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.text.SimpleDateFormat;
  6 import java.util.ArrayList;
  7 import java.util.Date;
  8 import java.util.HashMap;
  9 import java.util.Iterator;
 10 import java.util.List;
 11 import java.util.Map;
 12 import myFileListener.FileMd5;
 13 
 14 /**
 15  * @author jyroo
 16  * myfilelistener
 17  */
 18 @SuppressWarnings("unused")
 19 public class myFileListener {
 20     HashMap<String, String> hashmap = new HashMap<>(); //存放hash键值对
 21     List<String> file_in = new ArrayList<String>();
 22     List<String> file_ex = new ArrayList<String>();
 23     @SuppressWarnings("static-access")
 24     public void iteratorPath(String dir, List<String> file_in, List<String> file_ex) {
 25         while(true) {
 26             List<String> pathName = new ArrayList<String>();  //存放文件名
 27             File file = new File(dir);
 28             File[] files = file.listFiles();   //返回某个目录下所有文件和目录的绝对路径  return file[]
 29             if(files != null) {
 30                 for(File each_file : files) {
 31                     if(each_file.isFile()) {      // 如果是文件
 32                         int jui=2, juj=2;
 33                         if(file_in.size()!=0) {
 34                             jui = 0;
 35                             for(String strin : file_in) {
 36                                 if(each_file.getName().indexOf(strin)==-1) {
 37                                     jui = 0;
 38                                 }
 39                                 if(each_file.getName().indexOf(strin)!=-1) {
 40                                     jui = 1;
 41                                 }
 42                             }
 43                         }
 44                         if(file_ex.size()!=0) {
 45                             juj = 0;
 46                             for(String strex : file_ex) {
 47                                 if(each_file.getName().indexOf(strex)!=-1) {
 48                                     juj = 1;                                
 49                             }
 50                         }
 51                         if(juj==1||jui==0) {
 52                             continue;
 53                         }
 54                         pathName.add(each_file.getName());       //存储文件名   
 55                         
 56                         String file_path = each_file.getAbsolutePath();    //获取文件的绝对路径
 57                         
 58                         try {
 59                             FileMd5 mymd5 = new FileMd5();
 60                             String md5_value = mymd5.fileMd5(file_path);    //生成文件对应的hash值
 61                             if(hashmap.get(each_file.getName())==null) {
 62                                 System.out.println("文件夹:" + dir + "中的文件:" + each_file.getName() + "为新建文件!时间为:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
 63                                 hashmap.put(each_file.getName(), md5_value);    //以文件名作为key,hash值作为value存储到hashmap中
 64                             }
 65                             if(!hashmap.get(each_file.getName()).equals(md5_value)) {
 66                                 System.out.println("文件夹:" + dir + "中的文件:" + each_file.getName() + "被更新!时间为:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
 67                                 hashmap.put(each_file.getName(), md5_value);
 68                             }
 69                         } catch (Exception e) {
 70                             System.out.println("发生 "+e+" 的错误!!时间为" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
 71                         }
 72                     }
 73     //                    }else if(each_file.isDirectory()) {       //如果是文件夹
 74     //                        //iteratorPath(each_file.getAbsolutePath());   //递归遍历
 75     //                    }
 76                     }
 77                 }
 78                 try {
 79                     int juk;
 80                     for(String key : hashmap.keySet()) {
 81                         if(!pathName.contains(key)) {
 82                             System.out.println("文件夹:" + dir + "中的文件:" + key + "的文件已被删除!时间为:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
 83                             hashmap.remove(key);
 84                         }
 85                     }
 86                 }catch(Exception e) {
 87                     System.out.println(e);
 88                 }
 89             }
 90         }
 91     }
 92     
 93     public static void main(String[] args) {
 94         myFileListener file_walk = new myFileListener();
 95         List<String> file_ex = new ArrayList<String>();
 96         List<String> file_in = new ArrayList<String>();
 97         file_ex.add(".rec");
 98         //file_in.add("hi");
 99         file_walk.iteratorPath("E:\\tmp\\", file_in, file_ex);
100         for(String key:file_walk.hashmap.keySet()){
101             System.out.println("Key: "+key+" Value: "+file_walk.hashmap.get(key));
102         }
103     }    
104     
105 }

 

fileWalk.java

package myFileListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

@SuppressWarnings("unused")
public class fileWalk {
    List<String> pathName = new ArrayList<String>();
    public void iteratorPath(String dir) {
        File file = new File(dir);
        File[] files = file.listFiles();   //listFiles是获取该目录下所有文件和目录的绝对路径  return file[]
        if(files != null) {
            for(File each_file : files) {
                if(each_file.isFile()) {
                    pathName.add(each_file.getName());
                }else if(each_file.isDirectory()) {
                    iteratorPath(file.getAbsolutePath());
                }
            }
        }
    }

    public static void main(String[] args) {
        fileWalk file_walk = new fileWalk();
        file_walk.iteratorPath("E:\\tmp\\");
        for(String list : file_walk.pathName) {
            System.out.println(list);
        }
    }
}

 

posted @ 2019-03-22 12:06  JYRoy  阅读(615)  评论(0编辑  收藏  举报