當前位置:首頁 » 文件管理 » java監聽文件夾

java監聽文件夾

發布時間: 2022-05-23 13:37:50

java 每隔過一段時間監視文件夾並返新增加的文件名

如果JDK是java7,那麼可以使用WatchService,這個提供了非常底層的實現。

如果非要自己實現一個.建議使用java.util.Timer 類或者線程,定時執行文件檢查任務

下面比較啰嗦和簡陋的實現了需求,簡單的測試了,但不保證沒有bug,僅作參考

importjava.io.File;
importjava.io.IOException;
importjava.util.ArrayList;
publicclassFindNewFile{
publicstaticvoidmain(String[]args){
while(true){
Stringpath="c:\";//路徑
Filefile=newFile(path);
File[]files=file.listFiles();
ArrayList<File>list=newArrayList<File>();//文件對象存到list里
for(inti=0;i<files.length;i++){
list.add(files[i]);
}
try{
Thread.sleep(5000);//暫停5000毫秒
}catch(InterruptedExceptione){
e.printStackTrace();
}
Filefile2=newFile(path);
File[]files2=file2.listFiles();
ArrayList<File>list2=newArrayList<File>();
for(inti=0;i<files2.length;i++){
list2.add(files2[i]);
}
if(list2.size()>list.size()){
list2.removeAll(list);//用後來的文件夾對象減去之前的對象,
for(inti=0;i<list2.size();i++){
try{
System.out.println(list2.get(i).getCanonicalPath());
}catch(IOExceptione){
e.printStackTrace();
}
}
}else{
continue;
}
}
}
}

輸出

C:新建公文包
C:新建MicrosoftPublisher文檔.pub

基本實現了對新增文件的輸出文件名

Ⅱ java可以實現監聽文件夾內的文件變動嗎

可以自己寫定時任務,或者用現成的包。commons-io-2.3.jar 中,有實現文件監控的類。

可以學習這個:
http://blog.csdn.net/masternick/article/details/12197141

http://blog.csdn.net/u012083681/article/details/20689381

Ⅲ java 監聽指定目錄,有沒有新增的文件

使用 commons-io 中的文件監控

package org.demo.file;

import java.util.concurrent.TimeUnit;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

/**
* 文件監控測試
* @author
* @date 2010-11-16
* @file org.demo.file.FileMonitor.java
*/
public class FileMonitorTest {

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// 監控目錄
String rootDir = "d:\\Temp";
// 輪詢間隔 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();
}

Ⅳ Java 如何監控文件目錄的變化

JavaSE 1.7提供了相關的API,去監視文件或者文件夾的變動,主要的API都在java.nio.file下面,其大概流程如下:

packageorg.xdemo.superutil.j2se.filewatch;

importstaticjava.nio.file.LinkOption.NOFOLLOW_LINKS;

importjava.io.File;
importjava.io.IOException;
importjava.nio.file.FileSystems;
importjava.nio.file.FileVisitResult;
importjava.nio.file.Files;
importjava.nio.file.Path;
importjava.nio.file.Paths;
importjava.nio.file.SimpleFileVisitor;
importjava.nio.file.StandardWatchEventKinds;
importjava.nio.file.WatchEvent;
importjava.nio.file.WatchEvent.Kind;
importjava.nio.file.WatchKey;
importjava.nio.file.WatchService;
importjava.nio.file.attribute.BasicFileAttributes;
importjava.util.HashMap;
importjava.util.Map;

/**
*文件夾監控
*
*@authorGoofy<ahref="http://www.xdemo.org/">http://www.xdemo.org/</a>
*@Date2015年7月3日上午9:21:33
*/
publicclassWatchDir{

;
privatefinalMap<WatchKey,Path>keys;
privatefinalbooleansubDir;

/**
*構造方法
*
*@paramfile
*文件目錄,不可以是文件
*@paramsubDir
*@throwsException
*/
publicWatchDir(Filefile,booleansubDir,FileActionCallbackcallback)throwsException{
if(!file.isDirectory())
thrownewException(file.getAbsolutePath()+"isnotadirectory!");

this.watcher=FileSystems.getDefault().newWatchService();
this.keys=newHashMap<WatchKey,Path>();
this.subDir=subDir;

Pathdir=Paths.get(file.getAbsolutePath());

if(subDir){
registerAll(dir);
}else{
register(dir);
}
processEvents(callback);
}

@SuppressWarnings("unchecked")
static<T>WatchEvent<T>cast(WatchEvent<?>event){
return(WatchEvent<T>)event;
}

/**
*觀察指定的目錄
*
*@paramdir
*@throwsIOException
*/
privatevoidregister(Pathdir)throwsIOException{
WatchKeykey=dir.register(watcher,StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
keys.put(key,dir);
}

/**
*觀察指定的目錄,並且包括子目錄
*/
privatevoidregisterAll(finalPathstart)throwsIOException{
Files.walkFileTree(start,newSimpleFileVisitor<Path>(){
@Override
(Pathdir,BasicFileAttributesattrs)throwsIOException{
register(dir);
returnFileVisitResult.CONTINUE;
}
});
}

/**
*發生文件變化的回調函數
*/
@SuppressWarnings("rawtypes")
voidprocessEvents(FileActionCallbackcallback){
for(;;){
WatchKeykey;
try{
key=watcher.take();
}catch(InterruptedExceptionx){
return;
}
Pathdir=keys.get(key);
if(dir==null){
System.err.println("操作未識別");
continue;
}

for(WatchEvent<?>event:key.pollEvents()){
Kindkind=event.kind();

//事件可能丟失或遺棄
if(kind==StandardWatchEventKinds.OVERFLOW){
continue;
}

//目錄內的變化可能是文件或者目錄
WatchEvent<Path>ev=cast(event);
Pathname=ev.context();
Pathchild=dir.resolve(name);
Filefile=child.toFile();
if(kind.name().equals(FileAction.DELETE.getValue())){
callback.delete(file);
}elseif(kind.name().equals(FileAction.CREATE.getValue())){
callback.create(file);
}elseif(kind.name().equals(FileAction.MODIFY.getValue())){
callback.modify(file);
}else{
continue;
}

//ifdirectoryiscreated,andwatchingrecursively,then
//registeritanditssub-directories
if(subDir&&(kind==StandardWatchEventKinds.ENTRY_CREATE)){
try{
if(Files.isDirectory(child,NOFOLLOW_LINKS)){
registerAll(child);
}
}catch(IOExceptionx){
//ignoretokeepsamplereadbale
}
}
}

booleanvalid=key.reset();
if(!valid){
//移除不可訪問的目錄
//因為有可能目錄被移除,就會無法訪問
keys.remove(key);
//如果待監控的目錄都不存在了,就中斷執行
if(keys.isEmpty()){
break;
}
}
}
}

}

Ⅳ java中JFileChooser選擇文件時,能不能監聽文件夾的改變

voidaddChoosableFileFilter(FileFilter filter)

void setFileFilter(FileFilter filter) Sets the current file filter.

voidaddActionListener(ActionListener l)

Adds an ActionListener to the file chooser.

Ⅵ java如何在linux下監聽某個目錄下是否有文件改變

JDK 7 的nio2 WatchService可以監聽文件系統。

Oracle官方教程鏈接 http://docs.oracle.com/javase/tutorial/essential/io/notification.html

樣例代碼:

importstaticjava.nio.file.StandardWatchEventKinds.*;
Pathpath=Paths.get("/home");
WatchServicewatchService=FileSystems.getDefault().newWatchService();
WatchKeywatchKey=path.register(watchService,ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY);
/*
privatebooleannotDone=true;
while(notDone){
try{
WatchKeywatchKey=watchService.poll(60,TimeUnit.SECONDS);
List<WatchEvent.Kind<?>>events=watchKey.pollEvents();
for(WatchEventevent:events){
//.register
PathwatchedPath=(Path)watchKey.watchable();
//returnstheeventtype
=event.kind();
//returnsthecontextoftheevent
Pathtarget=(Path)event.context();
}
if(!watchKey.reset()){
...handlesituationnolongervalid
}
}catch(InterruptedExceptione){
Thread.currentThread().interrupt();
}
}
*/

Ⅶ 用java編寫 啟動一個線程,每隔一秒掃描一個指定的文件夾,監聽文件是刪除操作還是新建操作,(本

程序寫起來倒是不難 不過有個問題瑤瑤弄清楚,如果重命名不考慮的話:
如果該文件夾下原來有5個文件我新增了兩個,刪除了一個,按照你的說法是新增了1個,這種情況不用考慮嗎?
恢復了 馬上給你實現

Ⅷ java如何實現監視一個文件夾變化

靠後綴名是不行的,文件傳輸過程中,你本地文件系統已經穿件了該文件,是包含後綴的。
可以考慮使用文件大小, File.getTotalSpace(); 和File.lastModified() 來輔助判斷。

Ⅸ java實時監控區域網共享文件夾並復制文件到指定位置

首先要保證電腦A和電腦B網路可到達
然後在java里用一個線程(死循環)一直「監控」電腦A里的共享文件夾的大小 只要一有變化就讓電腦A里的共享文件夾下的所有文件復制一份到電腦B的共享文件夾下 然後把電腦A里的共享文件夾下的文件刪除

熱點內容
md5加密64 發布:2024-05-05 21:59:30 瀏覽:526
259pp頁面訪問升級 發布:2024-05-05 21:47:51 瀏覽:88
迅雷阻止上傳 發布:2024-05-05 21:26:19 瀏覽:913
資料庫運維題 發布:2024-05-05 21:21:47 瀏覽:961
RM魔塔編程 發布:2024-05-05 21:21:47 瀏覽:285
matlab獲取文件夾 發布:2024-05-05 21:12:24 瀏覽:291
一根式演算法 發布:2024-05-05 21:12:23 瀏覽:955
php無刷新 發布:2024-05-05 21:08:11 瀏覽:982
搭建一個流媒體伺服器 發布:2024-05-05 20:40:59 瀏覽:667
2017中超資料庫 發布:2024-05-05 20:37:25 瀏覽:379