How do I programmatically detect a change in a directory?
28 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2013-3-11
编辑: MathWorks Support Team
2022-10-14
I want to be able to automatically process a new data file when one appears in a particular folder.
采纳的回答
MathWorks Support Team
2022-10-14
编辑: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 个评论
Walter Roberson
2018-7-2
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
2018-7-2
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
更多回答(0 个)
另请参阅
类别
在 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!