A method for actively checking folder for new files?

18 ビュー (過去 30 日間)
Mike Bocchinfuso
Mike Bocchinfuso 2017 年 2 月 1 日
コメント済み: jerome maire 2018 年 11 月 27 日
hello all:
I'm trying to implement code that, once compiled and run, would actively check a specified folder regularly (for example, every 5 seconds) to look for the newest file added, and then perform some task to it (an image processing function that I've written).
I found this example which is similar to what I'm doing , and does work somewhat - in that it is able to report back that that there aren't any new files made while checking every 5 seconds. I'm just using that "new files found" text output as a quick check that it's actually checking.
however, when I add a test file to the specified folder while it's running, the program does not report back that new files have been found. it reports "new files found" on the first text output when run, but not on the following 5-second readouts.
here's the code as it stands right now:
myFolder = 'C:\Users\Documents\image_detection\sample_images\10192016\';
dir_content = dir('myFolder');
filenames = {dir_content.name};
current_files = filenames;
while true
pause(5)
dir_content = dir;
filenames = {dir_content.name};
new_files = setdiff(filenames,current_files);
if ~isempty(new_files)
% deal with the new files
current_files = filenames;
fprintf('new files found\n')
else
fprintf('no new files\n')
end
end

回答 (1 件)

Jan
Jan 2017 年 2 月 1 日
編集済み: Jan 2017 年 2 月 1 日
You need two small modifications:
myFolder = 'C:\Users\Documents\image_detection\sample_images\10192016\';
dir_content = dir(myFolder); % Without quotes, Not: dir('myFolder')
filenames = {dir_content.name};
current_files = filenames;
while true
pause(5)
dir_content = dir(myFolder); % Not: dir;
...
The code can be simplified:
myFolder = 'C:\Users\Documents\image_detection\sample_images\10192016\';
olddir = dir(myFolder);
while true
pause(5)
newdir = dir(myFolder);
if ~isqual(newdir, olddir)
fprintf('new files found\n');
olddir = newdir;
else
fprintf('no new files\n')
end
end
Think of using an active approach:
w = System.IO.FileSystemWatcher(myFolder);
w.NotifyFilter = System.IO.NotifyFilters.LastWrite;
addlistener(w, 'Changed', @(x,y) disp('Modified'));
w.EnableRaisingEvents = true;
But if you want to compile this: It seems like there is a problem.
  3 件のコメント
jcledfo2
jcledfo2 2017 年 12 月 16 日
Jan Simon, how would you use the active approach to initialize an m code and pass the filename when the new file is added to the folder?
jerome maire
jerome maire 2018 年 11 月 27 日
There is a typo in your suggested simplified code: should use isequal rather than isqual:
(if ~isequal(newdir, olddir))

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by