How do I programmatically detect a change in a directory?

28 visualizaciones (últimos 30 días)
I want to be able to automatically process a new data file when one appears in a particular folder.

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 14 de Oct. de 2022
Editada: MathWorks Support Team el 14 de Oct. de 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 comentarios

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre File Operations en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by