자바 캡 처 파일 변화 방법

2271 단어
더 읽 기
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class FileMonitorTest {
	
	static long pos = 0;

	public static void main(String[] args) throws Exception {
		//     
		String rootDir = "E:\\";
		//      5  
		long interval = TimeUnit.SECONDS.toMillis(5);
		//
		FileAlterationObserver observer = new FileAlterationObserver(rootDir, FileFilterUtils.and(
				FileFilterUtils.fileFileFilter(), FileFilterUtils.suffixFileFilter(".java")), null);
		observer.addListener(new MyFileListener());
		FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
		//     
		monitor.start();
	}

}

class MyFileListener extends FileAlterationListenerAdaptor {
	@Override
	public void onFileCreate(File file) {
		System.out.println("[  ]:" + file.getAbsolutePath());
	}

	@Override
	public void onFileChange(File file) {
		System.out.println("[  ]:" + file.getAbsolutePath());
		try {
			RandomAccessFile random = new RandomAccessFile(file, "r");
			
			if (FileMonitorTest.pos == 0) {
				FileMonitorTest.pos = random.length();
			}
			
			random.seek(FileMonitorTest.pos);
			String line;
			while((line = random.readLine()) != null) {
				System.out.println(line);
			}
			FileMonitorTest.pos = random.getFilePointer();
			random.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onFileDelete(File file) {
		System.out.println("[  ]:" + file.getAbsolutePath());
	}
}

좋은 웹페이지 즐겨찾기