JNotify对文件夹进行监管添加文件、删除文件、文件重命
下载好JNotify,里面有两个文件分别是jnotify.dll和jnotify_64bit.dll ,将这两个文件放到C:\Program Files\Java\jre7\bin下面就好(本地安装的jre的bin目录下,我用的是ssm框架)
public class TestFile {
public static void main(String[] args) {
//监控文件夹是否发生变化 下满这个方法不合适
try {
System.out.println(“进入监管”);
new TestFile().sampleTest();
} catch (Exception e) {
e.printStackTrace();
}
}
public void sampleTest() throws Exception{
//监控文件路径
String path = "D:\\test";
//设置参数 指定你关心的事件 或者 JNotify.FILE_ANY 任意事件
int mask = JNotify.FILE_CREATED
| JNotify.FILE_DELETED
| JNotify.FILE_MODIFIED
| JNotify.FILE_RENAMED ;
//好像是观察子目录
boolean watchSubtree = true;
//最后一个参数 继承了JNotifyListener 代码在最后
int watchId = JNotify.addWatch(path, mask, watchSubtree, new Listener() ); //返回一个watch的ID
//Thread.sleep(5000);//监管时间设置
//boolean resule = JNotify.removeWatch(watchId);//通过watchID删除watch
//if(!resule){ //删除失败 }
//sampleTest();//如果不回调一下,监管时间结束后就不会在重新进入监管模式
}
//拷贝方法 新增文件后 拷贝到另一目录下 操作如下
public void saveServer(String oldpath ){
try {
String newPath="D:\\newTest";//保存到新的文件夹路径
File newFile = new File(newPath);//得到新文件夹对象
if(!newFile.exists()){
(new File(newPath)).mkdirs(); //没有文件夹 就创建一个
}
File oldFile = new File(oldpath);
String[] oldFileList = oldFile.list();//得到旧的文件夹中的文件路径
File temp = null;
for(int i = 0; i<oldFileList.length;i++){//循环的得到旧文件夹中的所有文件并复制到新文件夹中
if(oldpath.endsWith(File.separator)){//判断路径最后是不是以“\”结尾
temp = new File(oldpath+oldFileList[i]);
}else{
temp = new File(oldpath+File.separator+oldFileList[i]);
}
if(temp.isFile()){
String name =newPath+"\\"+(temp.getName().toString());
System.out.println("加上文件名后的新路径"+name);
File fileN = new File(name);
if(!fileN.exists()){
FileOutputStream out = new FileOutputStream(name);
FileInputStream input = new FileInputStream(temp);
byte[] by = new byte[1024];
int len;
try {
while ((len=input.read(by)) != -1) {
out.write(by, 0, len);
}
out.flush();
out.close();
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//继承了JNotifyListener
public class Listener implements JNotifyListener {
@Override
public void fileRenamed(int arg0, String arg1, String arg2, String arg3) {
// TODO Auto-generated method stub
System.out.println(“renamed”+arg0+arg1+"------"+arg2+"--------"+arg3);
}
@Override
public void fileModified(int arg0, String arg1, String arg2) {
// TODO Auto-generated method stub
System.out.println("modified"+arg0+arg1+"------"+arg2);
}
@Override
public void fileDeleted(int arg0, String arg1, String arg2) {
// TODO Auto-generated method stub
System.out.println("deleted"+arg0+arg1+"------"+arg2);
}
@Override
public void fileCreated(int arg0, String oldpath, String arg2) {
System.out.println("created文件夹新增文件"+arg0+oldpath+"------"+arg2);
TestFile tt = new TestFile();
tt.saveServer(oldpath); //调用 拷贝方法
}
}