How do I programmatically detect a change in a directory?

28 次查看(过去 30 天)
I want to be able to automatically process a new data file when one appears in a particular folder.

采纳的回答

MathWorks Support Team
编辑:MathWorks Support Team 2022-10-14
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 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by