文件监视器

1.在web.xml配置文件监视器。
  <listener>
<listener-class>com.wgj.filter.FileModifyListener
</listener-class>
</listener>

2.监视器实现FileModifyListener.java
package com.wgj.filter;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

public class FileModifyListener implements ServletContextListener {

FileThread fileThread;
Logger log = Logger.getLogger(FileModifyListener.class);
public FileModifyListener() {
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}

@Override
public void contextInitialized(ServletContextEvent sce) {
fileThread = new FileThread();
fileThread.setDaemon(true);//作为后台线程运行
log.debug("File Listener Initialized: OK" );
try {
// System.out.println("File Listener Initialized: OK");
fileThread.start();
} catch(Exception e) {
log.debug("File Listener contextInitialized:",e);
}
}

}


3.线程实现类FileThread.java
package com.wgj.home;

import java.io.File;

import javax.servlet.ServletContext;

public class FileThread extends Thread {
private File fileDir = null;
private String monitorPath = null;
private String storePath = null;
FileMonitor monitorFileDir =null;
FileMonitor monitorFile =null;

public FileThread() {
monitorPath = "c:\\";
storePath = "e:\";
FileMonitor monitorFileDir = new FileMonitor(1000);
FileMonitor monitorFile = new FileMonitor(1000);
fileDir = new File(monitorPath);
monitorFileDir.addFile(fileDir);
monitorFileDir.addListener(new MonitorFileDirChanger(monitorFile, fileDir));
File[] files = fileDir.listFiles();
for (int i = 0; i < files.length; i++) {
monitorFile.addFile(files[i]);
monitorFile.addListener(new MonitorFileChanger());
}
}

public void run() {
while (!false)
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}

private class MonitorFileChanger implements FileListener {
public void fileChanged(File file) {
FileOperator fileCopy = new FileOperator();
fileCopy.copyFile(monitorPath + "\\" + file.getName(), storePath + file.getName());
}
}

private class MonitorFileDirChanger implements FileListener {
FileMonitor monitorFile;
File fileDir;

public MonitorFileDirChanger(FileMonitor monitorFile, File fileDir) {
this.monitorFile = monitorFile;
this.fileDir = fileDir;
}

public void fileChanged(File file) {
monitorFile.removeAllListener();
File[] files = fileDir.listFiles();
for (int i = 0; i < files.length; i++) {
monitorFile.addFile(files[i]);
monitorFile.addListener(new MonitorFileChanger());
}
FileOperator fileCopy = new FileOperator();
fileCopy.copyFolder(monitorPath, storePath);
}
}
}


4.其他工具类
4.1 FileListener.java
package com.wgj.home;

import java.io.File;

/**
* Interface for listening to disk file changes.
* @see FileMonitor
*
* @author <a href="mailto:jacob.dreyer@geosoft.no">Jacob Dreyer</a>
*/
public interface FileListener
{
/**
* Called when one of the monitored files are created, deleted
* or modified.
*
* @param file File which has been changed.
*/
void fileChanged (File file);
}


4.2 FileMonitor.java
package com.wgj.home;

import java.util.*;
import java.io.File;
import java.lang.ref.Reference;//WeakReference;


/**
* Class for monitoring changes in disk files.
* Usage:
*
* 1. Implement the FileListener interface.
* 2. Create a FileMonitor instance.
* 3. Add the file(s)/directory(ies) to listen for.
*
* fileChanged() will be called when a monitored file is created,
* deleted or its modified time changes.
*
* @author <a href="mailto:jacob.dreyer@geosoft.no">Jacob Dreyer</a>
*/
public class FileMonitor
{
private Timer timer_;
private HashMap files_; // File -> Long
private Collection listeners_; // of WeakReference(FileListener)


/**
* Create a file monitor instance with specified polling interval.
*
* @param pollingInterval Polling interval in milli seconds.
*/
public FileMonitor (long pollingInterval)
{
files_ = new HashMap();
listeners_ = new ArrayList();

timer_ = new Timer (true);
timer_.schedule (new FileMonitorNotifier(), 0, pollingInterval);
}



/**
* Stop the file monitor polling.
*/
public void stop()
{
timer_.cancel();
}


/**
* Add file to listen for. File may be any java.io.File (including a
* directory) and may well be a non-existing file in the case where the
* creating of the file is to be trepped.
* <p>
* More than one file can be listened for. When the specified file is
* created, modified or deleted, listeners are notified.
*
* @param file File to listen for.
*/
public void addFile (File file)
{
if (!files_.containsKey (file)) {
long modifiedTime = file.exists() ? file.lastModified() : -1;
files_.put (file, new Long (modifiedTime));
}
}



/**
* Remove specified file for listening.
*
* @param file File to remove.
*/
public void removeFile (File file)
{
files_.remove (file);
}



/**
* Add listener to this file monitor.
*
* @param fileListener Listener to add.
*/
public void addListener (FileListener fileListener)
{
// Don't add if its already there
for (Iterator i = listeners_.iterator(); i.hasNext(); ) {
// Reference reference = (Reference) i.next();

FileListener listener = (FileListener) i.next();//reference.get();
if (listener == fileListener)
return;
}

// Use WeakReference to avoid memory leak if this becomes the
// sole reference to the object.
listeners_.add (fileListener);//new Reference (
}



/**
* Remove listener from this file monitor.
*
* @param fileListener Listener to remove.
*/
public void removeListener (FileListener fileListener)
{
for (Iterator i = listeners_.iterator(); i.hasNext(); ) {
// Reference reference = (Reference) i.next();
FileListener listener = (FileListener) i.next();//reference.get();
if (listener == fileListener) {
i.remove();
break;
}
}
}

/**
* Remove listener from this file monitor.
*
* @param fileListener Listener to remove.
*/
public void removeAllListener ()
{
for (Iterator i = listeners_.iterator(); i.hasNext(); ) {
// Reference reference = (Reference) i.next();
FileListener listener = (FileListener) i.next();//reference.get();
i.remove();
}
}



/**
* This is the timer thread which is executed every n milliseconds
* according to the setting of the file monitor. It investigates the
* file in question and notify listeners if changed.
*/
private class FileMonitorNotifier extends TimerTask
{
public void run()
{
// Loop over the registered files and see which have changed.
// Use a copy of the list in case listener wants to alter the
// list within its fileChanged method.
Collection files = new ArrayList (files_.keySet());

for (Iterator i = files.iterator(); i.hasNext(); ) {
File file = (File) i.next();
long lastModifiedTime = ((Long) files_.get (file)).longValue();
long newModifiedTime = file.exists() ? file.lastModified() : -1;

// Chek if file has changed
if (newModifiedTime != lastModifiedTime) {

// Register new modified time
files_.put (file, new Long (newModifiedTime));

// Notify listeners
for (Iterator j = listeners_.iterator(); j.hasNext(); ) {
//Reference reference = (Reference) j.next();
FileListener listener = (FileListener) j.next();

// Remove from list if the back-end object has been GC'd
if (listener == null)
j.remove();
else
listener.fileChanged (file);
}
}
}
}
}


/**
* Test this class.
*
* @param args Not used.
*/
public static void main (String args[])
{
// Create the monitor
FileMonitor monitor = new FileMonitor (1000);
// Add some files to listen for
monitor.addFile (new File ("E:\\deploy\\test"));
monitor.addFile (new File ("E:\\deploy\\test\\1.txt"));
// Add a dummy listener
monitor.addListener (monitor.new TestListener());
// Avoid program exit
while (!false)
{

try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}


private class TestListener implements FileListener {
public void fileChanged (File file) {
System.out.println ("File changed: " + file);
}
}
}


4.3 FileOperator.java

package com.wgj.home;

import java.io.*;


public class FileOperator {

public FileOperator() {
}

/**
* 新建目录
* @param folderPath String 如 c:/fqf
* @return boolean
*/
public void newFolder(String folderPath) {
try {
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
if (!myFilePath.exists()) {
myFilePath.mkdir();
}
}
catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();
}
}

/**
* 新建文件
* @param filePathAndName String 文件路径及名称 如c:/fqf.txt
* @param fileContent String 文件内容
* @return boolean
*/
public void newFile(String filePathAndName, String fileContent) {

try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
String strContent = fileContent;
myFile.println(strContent);
resultFile.close();

}
catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();

}

}

/**
* 删除文件
* @param filePathAndName String 文件路径及名称 如c:/fqf.txt
* @param fileContent String
* @return boolean
*/
public void delFile(String filePathAndName) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
java.io.File myDelFile = new java.io.File(filePath);
myDelFile.delete();

}
catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();

}

}

/**
* 删除文件夹
* @param filePathAndName String 文件夹路径及名称 如c:/fqf
* @param fileContent String
* @return boolean
*/
public void delFolder(String folderPath) {
try {
delAllFile(folderPath); //删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //删除空文件夹

}
catch (Exception e) {
System.out.println("删除文件夹操作出错");
e.printStackTrace();

}

}

/**
* 删除文件夹里面的所有文件
* @param path String 文件夹路径 如 c:/fqf
*/
public void delAllFile(String path) {
File file = new File(path);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
}
else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
delFolder(path+"/"+ tempList[i]);//再删除空文件夹
}
}
}

/**
* 复制单个文件
* @param oldPath String 原文件路径 如:c:/fqf.txt
* @param newPath String 复制后路径 如:f:/fqf.txt
* @return boolean
*/
public void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}

/**
* 复制整个文件夹内容
* @param oldPath String 原文件路径 如:c:/fqf
* @param newPath String 复制后路径 如:f:/fqf/ff
* @return boolean
*/
public void copyFolder(String oldPath, String newPath) {

try {
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
File a=new File(oldPath);
//System.out.println("oldPath:"+oldPath);
String[] file=a.list();
File temp=null;
for (int i = 0; i < file.length; i++) {
if(oldPath.endsWith(File.separator)){
temp=new File(oldPath+file[i]);
}
else{
temp=new File(oldPath+File.separator+file[i]);
}

if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" +
(temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ( (len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if(temp.isDirectory()){//如果是子文件夹
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
}
}
}
catch (Exception e) {
System.out.println("copying all file error");//复制整个文件夹内容操作出错
e.printStackTrace();

}
}

/**
* 移动文件到指定目录
* @param oldPath String 如:c:/fqf.txt
* @param newPath String 如:d:/fqf.txt
*/
public void moveFile(String oldPath, String newPath) {
copyFile(oldPath, newPath);
delFile(oldPath);

}

/**
* 移动文件到指定目录
* @param oldPath String 如:c:/fqf.txt
* @param newPath String 如:d:/fqf.txt
*/
public void moveFolder(String oldPath, String newPath) {
copyFolder(oldPath, newPath);
delFolder(oldPath);

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值