How do I programmatically detect a change in a directory?

27 ビュー (過去 30 日間)
MathWorks Support Team
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
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
Walter Roberson 2018 年 7 月 2 日

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by