A method for actively checking folder for new files?
Ältere Kommentare anzeigen
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
Antworten (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;
3 Kommentare
per isakson
am 9 Aug. 2017
Bearbeitet: per isakson
am 9 Aug. 2017
Could "But if you want to compile this: It seems like there is a problem." possibly be related to https://uk.mathworks.com/support/bugreports/details/560506?partial=collapsed?
jcledfo2
am 16 Dez. 2017
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
am 27 Nov. 2018
There is a typo in your suggested simplified code: should use isequal rather than isqual:
(if ~isequal(newdir, olddir))
Kategorien
Mehr zu File Operations finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!