A method for actively checking folder for new files?
조회 수: 26 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
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;
댓글 수: 3
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
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 Exchange에서 File Operations에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!