在不使用WatchService的情况下检测Java中的文件更改
我创建了一个文件检查器,每X秒检查一次文件的更改。问题是,如果我使用WatchService检查文件,即使我触摸文件,它也会发送修改事件。我可以检查在不使用WatchService的情况下检测Java中的文件更改,java,Java,我创建了一个文件检查器,每X秒检查一次文件的更改。问题是,如果我使用WatchService检查文件,即使我触摸文件,它也会发送修改事件。我可以检查文件的.lenght,但是如果我的更改没有改变文件大小怎么办?知道如何检测文件更改吗 这是我的代码(我正在使用lastModified()方法一段时间) 在其他目录中维护该文件的副本 例如,我们将文件放在桌面上,在C:中维护文件副本,并检查是否存在任何差异 File source = new File(""C://Desktop//filename
文件的.lenght
,但是如果我的更改没有改变文件大小怎么办?知道如何检测文件更改吗
这是我的代码(我正在使用lastModified()
方法一段时间)
在其他目录中维护该文件的副本 例如,我们将文件放在
桌面上
,在C:
中维护文件副本,并检查是否存在任何差异
File source = new File(""C://Desktop//filename.txt");
File dest = new File("C://temp//cache-filename.txt");
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
然后保持一个计时器,每次都给你的朋友打电话
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if(comapreTwoFiles("C://temp//cache-filename.txt", "C://Desktop//filename.txt")){
System.out.println("File is changed");
//change your cache file
}
}
}, 2*60*1000, 2*60*1000);
public boolean compareTwoFiles(String path1, String path2)
throws IOException {
File file1 = new File(path1);
File file2 = new File(path2);
BufferedReader br1 = new BufferedReader(new FileReader(file1));
BufferedReader br2 = new BufferedReader(new FileReader(file2));
String thisLine = null;
String thatLine = null;
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
while ((thisLine = br1.readLine()) != null) {
list1.add(thisLine);
}
while ((thatLine = br2.readLine()) != null) {
list2.add(thatLine);
}
br1.close();
br2.close();
return list1.equals(list2);
}
Timer=new Timer();
timer.scheduleAtFixedRate(新TimerTask(){
@凌驾
公开募捐{
if(ComaNetofiles(“C://temp//cache filename.txt”、“C://Desktop//filename.txt”)){
System.out.println(“文件已更改”);
//更改缓存文件
}
}
}, 2*60*1000, 2*60*1000);
公共布尔比较文件(字符串路径1、字符串路径2)
抛出IOException{
文件file1=新文件(路径1);
文件file2=新文件(路径2);
BufferedReader br1=新的BufferedReader(新文件读取器(文件1));
BufferedReader br2=新的BufferedReader(新文件读取器(文件2));
字符串thisLine=null;
字符串thatLine=null;
List list1=新的ArrayList();
List list2=新的ArrayList();
而((thisLine=br1.readLine())!=null){
列表1.添加(此行);
}
而((thatLine=br2.readLine())!=null){
列表2.添加(该行);
}
br1.close();
br2.close();
返回列表1.equals(列表2);
}
也许java NIO能帮上忙
BasicFileAttributes attr=Files.readAttributes(文件,BasicFileAttributes.class);
System.out.println(“lastModifiedTime:+attr.lastModifiedTime()) 使用MD5的校验和文件
public class MD5 {
public static String getMD5(String input) {
try {
byte[] thedigest = MessageDigest.getInstance("MD5").digest(input.getBytes("UTF-8"));
BigInteger number = new BigInteger(1, thedigest);
String hashtext = number.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static boolean checksum(String filePath, String hashCode) {
try {
return getFileHash(filePath).equals(hashCode);
} catch (Exception ex) {
return false;
}
}
public static String getFileHash(String filePath) {
InputStream fis = null;
try {
fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
byte[] b = complete.digest();
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
} catch (IOException | NoSuchAlgorithmException ex) {
Logger.getLogger(MD5.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException(ex);
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException ex) {
Logger.getLogger(MD5.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
公共类MD5{
公共静态字符串getMD5(字符串输入){
试一试{
byte[]thedigest=MessageDigest.getInstance(“MD5”).digest(input.getBytes(“UTF-8”);
BigInteger数=新的BigInteger(1,最大值);
字符串hashtext=number.toString(16);
//现在,如果你真的想要全部32个字符,我们需要零填充它。
while(hashtext.length()<32){
hashtext=“0”+hashtext;
}
返回hashtext;
}捕获(无此算法异常|不支持编码异常e){
抛出新的运行时异常(e);
}
}
公共静态布尔校验和(字符串文件路径、字符串哈希代码){
试一试{
返回getFileHash(filePath).equals(hashCode);
}捕获(例外情况除外){
返回false;
}
}
公共静态字符串getFileHash(字符串文件路径){
InputStream fis=null;
试一试{
fis=新文件输入流(文件路径);
字节[]缓冲区=新字节[1024];
MessageDigest complete=MessageDigest.getInstance(“MD5”);
国际货币联盟;
做{
numRead=fis.read(缓冲区);
如果(numRead>0){
完成。更新(缓冲区,0,numRead);
}
}而(numRead!=-1);
字节[]b=complete.digest();
字符串结果=”;
for(int i=0;i
您可以检查MD5校验和,而不是文件大小:
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
public class Main {
public static byte[] getMD5Checksum(String filename) throws Exception {
InputStream fis = new FileInputStream(filename);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int aux;
do {
aux = fis.read(buffer);
if (aux > 0) {
md.update(buffer, 0, aux);
}
} while (aux != -1);
fis.close();
return md.digest();
}
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes)
sb.append(String.format("%02x", b & 0xff));
return sb.toString();
}
public static void main(String args[]) throws Exception {
System.out.println(toHexString(getMD5Checksum("/Users/irineuantunes/Desktop/testFile.txt")));
}
}
public class MD5 {
public static String getMD5(String input) {
try {
byte[] thedigest = MessageDigest.getInstance("MD5").digest(input.getBytes("UTF-8"));
BigInteger number = new BigInteger(1, thedigest);
String hashtext = number.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static boolean checksum(String filePath, String hashCode) {
try {
return getFileHash(filePath).equals(hashCode);
} catch (Exception ex) {
return false;
}
}
public static String getFileHash(String filePath) {
InputStream fis = null;
try {
fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
byte[] b = complete.digest();
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
} catch (IOException | NoSuchAlgorithmException ex) {
Logger.getLogger(MD5.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException(ex);
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException ex) {
Logger.getLogger(MD5.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
public class Main {
public static byte[] getMD5Checksum(String filename) throws Exception {
InputStream fis = new FileInputStream(filename);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int aux;
do {
aux = fis.read(buffer);
if (aux > 0) {
md.update(buffer, 0, aux);
}
} while (aux != -1);
fis.close();
return md.digest();
}
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes)
sb.append(String.format("%02x", b & 0xff));
return sb.toString();
}
public static void main(String args[]) throws Exception {
System.out.println(toHexString(getMD5Checksum("/Users/irineuantunes/Desktop/testFile.txt")));
}
}