下面列出了java.io.File#lastModified ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void handleGalleryShareFiles() {
File tempDirectory = getExternalTempDirectory();
if (tempDirectory == null) {
return;
}
long time = System.currentTimeMillis();
File[] files = tempDirectory.listFiles();
if (files != null) {
for (File tempFile : files) {
if (tempFile.getName().startsWith(GALLERY_SHARE_FILE_NAME_START)) {
boolean delete = tempFile.lastModified() + 60 * 60 * 1000 < time; // 1 hour
if (delete) {
tempFile.delete();
}
}
}
}
}
static int clearCacheFolder(final File dir, final int numDays) {
int deletedFiles = 0;
if (dir != null && dir.isDirectory()) {
try {
for (File child : dir.listFiles()) {
//first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
//then delete the files and subdirectories in this dir
//only empty directories can be deleted, so subdirs have been done first
if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
}
}
} catch (Exception e) {
Log.e("Info", String.format("Failed to clean the cache, error %s", e.getMessage()));
}
}
return deletedFiles;
}
public static boolean isACLsFileNewer(long time) {
boolean newer = false;
String confDir = System.getProperty(KMS_CONFIG_DIR);
if (confDir != null) {
Path confPath = new Path(confDir);
if (!confPath.isUriPathAbsolute()) {
throw new RuntimeException("System property '" + KMS_CONFIG_DIR +
"' must be an absolute path: " + confDir);
}
File f = new File(confDir, KMS_ACLS_XML);
// at least 100ms newer than time, we do this to ensure the file
// has been properly closed/flushed
newer = f.lastModified() - time > 100;
}
return newer;
}
@Override
protected int performCheck(File product, Boolean compareItem) throws PreconditionComparatorException {
// check product last modification time
long now = System.currentTimeMillis();
long lastModTime = product.lastModified();
long deltaInSecs = (now-lastModTime)/1000;
// reject this product
if (deltaInSecs>maxAgeInSeconds) {
LOG.log(Level.FINEST, "Product: "+product.getAbsolutePath()+" fails 'Last Modified' check: "+new Date(lastModTime));
return Boolean.FALSE.compareTo(compareItem);
// accept this product
} else {
LOG.log(Level.FINEST, "Product: "+product.getAbsolutePath()+" passes 'Last Modified' check: "+new Date(lastModTime));
return Boolean.TRUE.compareTo(compareItem);
}
}
/**
* Loads files in a path using basic filesystem callbacks
*
* @param path the path
* @param showHidden
* @return
*/
public static ArrayList<BaseFile> getFilesList(String path, boolean showHidden) {
File f = new File(path);
ArrayList<BaseFile> files = new ArrayList<>();
try {
if (f.exists() && f.isDirectory()) {
for (File x : f.listFiles()) {
long size = 0;
if (!x.isDirectory()) size = x.length();
BaseFile baseFile = new BaseFile(x.getPath(), parseFilePermission(x),
x.lastModified(), size, x.isDirectory());
baseFile.setName(x.getName());
baseFile.setMode(OpenMode.FILE);
if (showHidden) {
files.add(baseFile);
} else {
if (!x.isHidden()) {
files.add(baseFile);
}
}
}
}
} catch (Exception e) {
}
return files;
}
private void addDetails(List<Map<String, Object>> files, File dir, String name) {
Map<String, Object> details = new HashMap<>();
File aFile = new File(dir, name);
if (aFile.isDirectory()) return;
long sz = aFile.length();
Date lastModified = new Date(aFile.lastModified());
if (biggerThan != -1 && sz <= biggerThan)
return;
if (smallerThan != -1 && sz >= smallerThan)
return;
if (olderThan != null && lastModified.after(olderThan))
return;
if (newerThan != null && lastModified.before(newerThan))
return;
details.put(DIR, dir.getAbsolutePath());
details.put(FILE, name);
details.put(ABSOLUTE_FILE, aFile.getAbsolutePath());
details.put(SIZE, sz);
details.put(LAST_MODIFIED, lastModified);
files.add(details);
}
/**
* Returns the last replay (the latest replay) in the specified folder (recursive).
* @param startFolder folder to start searching in
* @param lastReplayFile the best candidate for being the last replay so far
* @return the last replay (the latest replay) in the specified folder (recursive)
* @see #getLastReplayFile()
*/
public static File getLastReplay( final File startFolder, File lastReplayFile ) {
long lastReplayTime = lastReplayFile == null ? 0 : lastReplayFile.lastModified();
final File[] files = startFolder.listFiles( GeneralUtils.SC2REPLAY_FILE_FILTER );
if ( files == null )
return lastReplayFile;
for ( int i = files.length - 1; i >= 0; i-- ) { // Prolly the last is the last, so in order to minimize assignments, go downwards...
final File file = files[ i ];
if ( file.isDirectory() ) {
lastReplayFile = getLastReplay( file, lastReplayFile );
lastReplayTime = lastReplayFile == null ? 0 : lastReplayFile.lastModified();
}
else
if ( file.lastModified() > lastReplayTime ) {
lastReplayFile = file;
lastReplayTime = file.lastModified();
}
}
return lastReplayFile;
}
public static void cleanupCache(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
long time = new Date().getTime();
File folder = getCacheFolder(context);
int days = Integer.parseInt(prefs.getString(SettingsFragment.PREF_SEARCH_CACHE, SettingsFragment.DEFAULT_SEARCH_CACHE));
for (File file : folder.listFiles())
if (file.lastModified() + days * 24 * 3600 * 1000L < time) {
Log.i(TAG, "Deleting " + file);
file.delete();
}
}
ConfigFilePoller(File configFile) {
this.file = configFile;
lastUpdatedAt = configFile.lastModified();
this.setName("sqoop-config-file-poller");
this.setDaemon(true);
loadSleepTime();
}
public static File[] getFiles(String directory, String wildcard, String excludeWildcard, long minStability) {
WildCardFilter filter = new WildCardFilter(wildcard);
File dir = new File(directory);
File[] files = dir.listFiles(filter);
WildCardFilter excludeFilter = null;
if (StringUtils.isNotEmpty(excludeWildcard)) {
excludeFilter = new WildCardFilter(excludeWildcard);
}
long lastChangedAllowed=minStability>0?new Date().getTime()-minStability:0;
List<File> result = new ArrayList<File>();
int count = (files == null ? 0 : files.length);
for (int i = 0; i < count; i++) {
File file = files[i];
if (!file.isFile()) {
continue;
}
if (excludeFilter!=null && excludeFilter.accept(dir, file.getName())) {
continue;
}
if (minStability>0 && file.lastModified()>lastChangedAllowed) {
continue;
}
result.add(file);
}
Collections.sort(result, new FileComparator());
return result.toArray(new File[0]);
}
private boolean isOutdated () {
boolean upToDate = dirstateSize == dirstateFile.length();
if (upToDate) {
for (Map.Entry<String, Long> e : interestingTimestamps.entrySet()) {
File f = new File(hgFolder, e.getKey());
long ts = f.lastModified();
// file is now either modified (higher ts) or deleted
if (e.getValue() < ts || e.getValue() > ts && ts == 0) {
upToDate = false;
break;
}
}
}
return !upToDate;
}
public static int clearCacheFolder(final File dir,
final int numDays) {
int deletedFiles = 0;
if (dir != null && dir.isDirectory()) {
try {
for (File child : dir.listFiles()) {
// first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child,
numDays);
}
// then delete the files and subdirectories in this dir
// only empty directories can be deleted, so subDirs have
// been done first
if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
}
}
} catch (Exception e) {
}
}
return deletedFiles;
}
private int compareByModifiedDateUp(File object1, File object2) {
long d1 = object1.lastModified();
long d2 = object2.lastModified();
if (d1 == d2) {
return 0;
} else {
return d1 > d2 ? 1 : -1;
}
}
public boolean hasntChangedSince(MFile file, long when) {
String idxPath = file.getPath();
if (!idxPath.endsWith(GBX9_IDX))
idxPath += GBX9_IDX;
File idxFile = GribIndexCache.getExistingFileOrCache(idxPath);
if (idxFile == null)
return true;
if (idxFile.lastModified() < file.getLastModified())
return true;
return 0 < when && idxFile.lastModified() < when;
}
/**
* 构造函数
*
* @param file 用户代码路径
* @param charset 用户代码编码
* @throws UnsupportedEncodingException 字符集异常
*/
public DynamicFunction(File file, String charset) throws UnsupportedEncodingException {
init();
String fileName = TFile.getFileName(file.getPath());
this.name = fileName.substring(0, fileName.lastIndexOf("."));
this.codeFile = file;
this.fileCharset = charset;
this.lastFileTimeStamp = file.lastModified();
DynamicCompilerManager.addFunction(this);
}
/**
* Start a new OMC server.
*/
private static void startServer() throws ConnectException {
File[] tmp = getOmcBinaryPaths();
File omcBinary = tmp[0];
File workingDirectory = new File(".");
/*
* Delete old object reference file. We need to do this because we're
* checking if the file exists to determine if the server has started
* or not (further down).
*/
File f = new File(getPathToObject());
long lastModified = 0;
if (f.exists()) {
lastModified = f.lastModified();
logOMCStatus("OMC object reference file is already on disk, we try to use it.");
if (existingCorbaFileIsNew) {
return;
}
logOMCStatus("OMC object reference file is already on disk, but is old, start a new server.");
}
String[] command = {omcBinary.getAbsolutePath(), "+c=" + corbaSessionName, "+d=interactiveCorba"};
try {
logOMCStatus("Running command " + command[0] + " " + command[1] + " " + command[2]);
logOMCStatus("Setting working directory to " + workingDirectory.getAbsolutePath());
ProcessStartThread pt = new ProcessStartThread(command, workingDirectory);
pt.start();
} catch (Exception e) {
e.printStackTrace();
logOMCStatus("Error running command " + e.getMessage());
logOMCStatus("Unable to start OMC, giving up.");
throw new ConnectException("Unable to start the OpenModelica Compiler. ");
}
logOMCStatus("Waiting for OMC CORBA object reference to appear on disk.");
existingCorbaFileIsNew = true;
/*
* Wait until the object exists on disk, but if it takes longer than
* 5 seconds, abort. (Very arbitrary 5 seconds..)
*/
int ticks = 0;
while (!f.exists() || (f.exists() && lastModified == f.lastModified())) {
try {
logOMCStatus("Waiting for OMC CORBA object reference to appear on disk ... for " + (ticks + 1) + " seconds");
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
ticks++;
/* If we've waited for around 5 seconds, abort the wait for OMC */
if (ticks > 50) {
logOMCStatus("No OMC object reference file created after approximately 50 seconds.");
logOMCStatus("It seems OMC does not want to start, giving up.");
throw new ConnectException("Unable to start the Open Modelica Compiler. Waited for 5 seconds, but it didn't respond.");
}
}
logOMCStatus("The new OMC object reference found.");
}
/**
* Returns the index directories that are applicable only for the given time
* span (times inclusive).
*
* @param startTime the start time of the query for which the indices are
* desired
* @param endTime the end time of the query for which the indices are
* desired
* @return the index directories that are applicable only for the given time
* span (times inclusive).
*/
public List<File> getIndexDirectories(final Long startTime, final Long endTime) {
if (startTime == null && endTime == null) {
return getIndexDirectories();
}
final List<File> dirs = new ArrayList<>();
lock.lock();
try {
// Sort directories so that we return the newest index first
final List<File> sortedIndexDirectories = getIndexDirectories();
Collections.sort(sortedIndexDirectories, new Comparator<File>() {
@Override
public int compare(final File o1, final File o2) {
final long epochTimestamp1 = getIndexStartTime(o1);
final long epochTimestamp2 = getIndexStartTime(o2);
return Long.compare(epochTimestamp2, epochTimestamp1);
}
});
for (final File indexDir : sortedIndexDirectories) {
// If the index was last modified before the start time, we know that it doesn't
// contain any data for us to query.
if (startTime != null && indexDir.lastModified() < startTime) {
continue;
}
// If the index was created after the given end time, we know it doesn't contain any
// data for us to query.
if (endTime != null) {
final long indexStartTime = getIndexStartTime(indexDir);
if (indexStartTime > endTime) {
continue;
}
}
dirs.add(indexDir);
}
return dirs;
} finally {
lock.unlock();
}
}
/**
* Gets the GTFS file via http from the configured URL urlStr and stores it
* in the configured directory dirName.
* <p>
* If file on web server last modified time is not newer than the local file
* then the file will not actually be downloaded.
* <p>
* If file is downloaded then users and e-mailed.
*/
public static void get() {
logger.info("Checking to see if GTFS should be downloaded "
+ "because it was modified. {}", url.getValue());
// Construct the getter
HttpGetFile httpGetFile =
new HttpGetFile(url.getValue(), dirName.getValue());
// If file hasn't been modified then don't want to download it
// since it can be large. Therefore determine age of previously
// downloaded file and use If-Modified-Since to only actually
// get the file if it is newer on the web server
File file = new File(httpGetFile.getFullFileName());
boolean fileAlreadyExists = file.exists();
if (fileAlreadyExists) {
// Get the last modified time of the local file. Add 10 minutes
// since the web server might be load balanced and the files
// on the different servers might have slightly different last
// modified times. To make sure that don't keep downloading
// from the different servers until get the file with most
// recent modified time add 10 minutes to the time to indicate
// that as long as the local file is within 10 minutes of the
// remote file that it is ok.
long lastModified = file.lastModified() + 10*Time.MS_PER_MIN;
httpGetFile.addRequestHeader("If-Modified-Since",
Time.httpDate(lastModified));
logger.debug("The file {} already exists so using "
+ "If-Modified-Since header of \"{}\" or {} msec.",
httpGetFile.getFullFileName(), Time.httpDate(lastModified),
lastModified);
}
try {
// Actually get the file from web server
int httpResponseCode = httpGetFile.getFile();
// If got a new file (instead of getting a NOT MODIFIED
// response) then send message to those monitoring so that
// the GTFS file can be processed.
if (httpResponseCode == HttpStatus.SC_OK) {
if (fileAlreadyExists)
logger.info("Got remote file because version on web server "
+ "is newer. Url={} dir={}",
httpGetFile.getFullFileName(), dirName.getValue());
else
logger.info("Got remote file because didn't have a local "
+ "copy of it. Url={} dir={}",
httpGetFile.getFullFileName(), dirName.getValue());
// Email message
String subject = "GTFS file was updated for "
+ AgencyConfig.getAgencyId();
String message = "For " + AgencyConfig.getAgencyId()
+ " the GTFS file " + url.getValue()
+ " was updated so was downloaded to "
+ httpGetFile.getFullFileName();
emailSender.send(MonitorBase.recipientsGlobal(), subject,
message);
// Make copy of GTFS zip file in separate directory for archival
archive(httpGetFile.getFullFileName());
} else if (httpResponseCode == HttpStatus.SC_NOT_MODIFIED) {
// If not modified then don't need to do anything
logger.info("Remote GTFS file {} not updated (got "
+ "HTTP NOT_MODIFIED status 304) since the local "
+ "one at {} has last modified date of {}",
url.getValue(), httpGetFile.getFullFileName(),
new Date(file.lastModified()));
} else {
// Got unexpected response so log issue
logger.error("Error retrieving remote GTFS file {} . Http "
+ "response code={}",
url.getValue(), httpResponseCode);
}
} catch (IOException e) {
logger.error("Error retrieving {} . {}",
url.getValue(), e.getMessage());
}
}
public WarInfo(File war) {
this.war = war;
this.lastChecked = war.lastModified();
if (!war.exists())
lastState = -1;
}
public FileInfo(final File file) {
this(file.getAbsolutePath(), file.length(), file.lastModified());
}