在java中目录被看做,在java中查看目录中的更改时避免检测不完整的文件

I am watching a directory for incoming files (using FileAlterationObserver from apache commons).

class Example implements FileAlterationListener {

public void prepare() {

File directory = new File("/tmp/incoming");

FileAlterationObserver observer = new FileAlterationObserver(directory);

observer.addListener(this);

FileAlterationMonitor monitor = new FileAlterationMonitor(10);

monitor.addObserver(observer);

monitor.start();

// ...

}

public void handleFile(File f) {

// FIXME: this should be called when the writes that

// created the file have completed, not before

}

public void onFileCreate(File f) {

handleFile(f);

}

public void onFileChange(File f) {

handleFile(f);

}

}

The files are written in place by processes that I have no control over.

The problem I have with that code is that my callback is triggered when the File is initially created. I need it to trigger when the file has been changed and the write to the file has completed. (maybe by detecting when the file stopped changing)

What's the best way to do that?

解决方案

I had a similar problem. At first I thought I could use the FileWatcher service, but it doesn't work on remote volumes, and I had to monitor incoming files via a network mounted drive.

Then I thought I could simply monitor the change in file size over a period of time and consider the file done once the file size had stabilized (as fmucar suggested). But I found that in some instances on large files, the hosting system would report the full size of the file it was copying, rather than the number of bytes it had written to disk. This of course made the file appear stable, and my detector would catch the file while it was still in the process of being written.

I eventually was able to get the monitor to work, by employing a FileInputStream exception, which worked wonderfully in detecting whether a file was being written to, even when the file was on a network mounted drive.

long oldSize = 0L;

long newSize = 1L;

boolean fileIsOpen = true;

while((newSize > oldSize) || fileIsOpen){

oldSize = this.thread_currentFile.length();

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

newSize = this.thread_currentFile.length();

try{

new FileInputStream(this.thread_currentFile);

fileIsOpen = false;

}catch(Exception e){}

}

System.out.println("New file: " + this.thread_currentFile.toString());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值