How do I programmatically detect a change in a directory?
74 views (last 30 days)
Show older comments
MathWorks Support Team
on 11 Mar 2013
Edited: MathWorks Support Team
on 14 Oct 2022
I want to be able to automatically process a new data file when one appears in a particular folder.
Accepted Answer
MathWorks Support Team
on 14 Oct 2022
Edited: MathWorks Support Team
on 14 Oct 2022
There is no built-in function for monitoring changes in directories.
Starting with R2009a, MATLAB supports .NET objects such as the FileSystemWatcher, which can be used to work around this issue:
.NET Events in the MATLAB Workspace
For older releases, to see if a file has appeared in a directory, use the EXIST or DIR functions in a TIMER callback function. Given below is a sample function which uses TIMER to check a directory's contents at 10-second intervals. It then checks the length (i.e., number of files) returned by DIR to see if a file has been added since the last check. The TIMER function is set to timeout after 500 seconds. It can also be executed without the timeout option.
function detectFile(dirName)
period = 10; %seconds between directory checks
timeout = 500; %seconds before function termination
dirLength = length(dir(dirName));
t = timer('TimerFcn', {@timerCallback, dirName, dirLength}, 'Period', period,'TaskstoExecute', uint8(timeout/period), 'executionmode', 'fixedrate');
start(t)
function timerCallback(src, eventdata, dirName, dirLength)
persistent my_dirLength;
persistent my_beginFlag;
if isempty(my_beginFlag)
my_dirLength = dirLength;
my_beginFlag = 0;
end
if length(dir(dirName)) > my_dirLength
disp('A new file is available')
my_dirLength = length(dir(dirName));
else
disp('No new files')
end
If you know the name of the file you are looking for, EXIST would provide more functionality than DIR. EXIST checks for the presence of a specific file, while DIR returns a list of directory contents.
3 Comments
Walter Roberson
on 2 Jul 2018
Jan posted example code for using .NET to look for directory changes at https://www.mathworks.com/matlabcentral/answers/352051-errors-with-polling-directory-for-new-files-to-process#answer_277367
Walter Roberson
on 2 Jul 2018
Guillaume posted Java code to watch files in https://www.mathworks.com/matlabcentral/answers/398152-listening-to-the-creation-deletion-of-a-file-with-specific-name#answer_317920
More Answers (0)
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!