源代码:
package com.oracle.cl;
import java.awt.AWTException;
import java.awt.Robot;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ViewFiles
{
public static void main(String[] args) throws IOException, AWTException
{
CrateFile100();
ViewFiles();
}
// 创建100个文件
public static void CrateFile100() throws IOException
{
File f=new File("D:\\hello1\\hello2\\hello3\\hello.txt");
// 获取文件的目录
File f2=new File(f.getPath().replace(f.getName(), ""));
if(!f2.exists())
{
f2.mkdirs();
}
for(int i=1;i<=100;i++)
{
File file=new File(f2,"hello"+i+".txt");
if(!file.exists())
{
file.createNewFile();
}
}
}
/*
* 监控哪个文件被修改过 如果该文件被修改过
* 则在控制台显示 文件的名称 在什么时间 被修改过
*/
public static void ViewFiles() throws AWTException
{
SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
Map<String,Long> map=new HashMap<>();
Robot robot=new Robot();
for(int i=1;i<=100;i++)
{
//获取文件夹的所有文件 项目一启动 获取该文件夹下所有文件的修改时间
File file=new File("D:\\hello1\\hello2\\hello3\\hello"+i+".txt");
map.put(file.getName(), file.lastModified());
}
while(true)
{
robot.delay(1000);
Map<String,Long> map2=new HashMap();
for(int i=1;i<=100;i++)
{
//获取该文件夹下所有文件的修改时间
File f=new File("D:\\hello1\\hello2\\hello3\\hello"+i+".txt");
map2.put(f.getName(),f.lastModified());
}
Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
for(;iterator.hasNext();)
{
String key = iterator.next();
long time1=map.get(key);
long time2=map2.get(key);
if(time1!=time2)
{
System.out.println(key+"在"+format.format(time2)+"被修改过");
map.put(key, time2);
}
}
}
}
}
运行后,在此路径下有100个文件:
每打开其中一个修改后,控制台输出修改的时间: