简体   繁体   中英

How to check if size of a file was modified from the last time in batch or java?

I have a script that reads a log from a remote machine and in case when some errors are in there, the lines with the errrors are copied to my computer in a Test.txt file . Here I will do some logic like send email if the size of this file is greater than 0 (this means errors found). The issue is that this script will send email every time even if the log will contain only 1 error.

So, what I am thinking to do is to check if the file from my computer has the size bigger than the last time size. I need to do this in batch or in java.

It would be possible to compare file size or last modification date of a file since last check by saving file size and/or last modification time into one more file and compare actual file size/last modification date with saved string in the additional file.

But much easier to use for this purpose is the archive attribute which is automatically always set if a file is modified. So all to do is remove the archive attribute from file once the data in the file were processed and check next if the archive attribute is set again because of a file modification.

Here is an example code:

@echo off
set "LogFile=C:\Temp\Errors.log"
"%SystemRoot%\system32\attrib.exe" "%LogFile%" | "%SystemRoot%\system32\findstr.exe" /B /L A 1>nul
if errorlevel 1 goto EndBatch

rem The log file has archive attribute set as modified since last check
echo File "%LogFile%" was modified since last check.

rem Remove the archive attribute from log file before reading the
rem contents of the log file and send the error lines via email.
rem Of course the archive attribute can be removed also after the
rem data of the log files were processed by additional batch code.
"%SystemRoot%\system32\attrib.exe" -A "%LogFile%"

:EndBatch
set LogFile=

The Windows standard application attrib.exe outputs the file attributes at beginning of the output line and after some spaces the file name. The output line starts with A if only the archive attribute is set and with a space if whether archive attribute nor any other attribute is set for the file.

The Windows standard application findstr.exe with options /B and /L searches for A at beginning of the line and if found terminates with exit code 0. But if the output line from attrib.exe does not start with A , the return value of findstr.exe is 1 assigned to environment variable ERRORLEVEL which means the archive attribute is not set on file and therefore the file was not modified since last check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM