List of usage examples for java.io File setLastModified
public boolean setLastModified(long time)
From source file:phex.util.FileUtils.java
/** * This method performce a multi fallback file rename operation to try to * work around the Java problems with rename operations. * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213298 * * @throws FileHandlingException//from w ww.ja v a2 s . co m */ public static void renameFileMultiFallback(File sourceFile, File destFile) throws FileHandlingException { if (destFile.exists()) { // cant rename to file that already exists throw new FileHandlingException(FileHandlingException.FILE_ALREADY_EXISTS); } if (!sourceFile.exists()) { return; } boolean succ = sourceFile.renameTo(destFile); if (succ) { NLogger.warn(FileUtils.class, "First renameTo operation worked!"); return; } NLogger.warn(FileUtils.class, "First renameTo operation failed."); // Try to run garbage collector to make the file rename operation work System.gc(); // Yield thread and to hope GC kicks in... Thread.yield(); // Try rename again... succ = sourceFile.renameTo(destFile); if (succ) { return; } NLogger.warn(FileUtils.class, "Second renameTo operation failed."); // Rename failed again... just perform a slow copy/delete operation FileInputStream input = null; FileOutputStream output = null; try { input = new FileInputStream(sourceFile); output = new FileOutputStream(destFile); long lengthLeft = sourceFile.length(); byte[] buffer = new byte[(int) Math.min(BUFFER_LENGTH, lengthLeft + 1)]; int read; while (lengthLeft > 0) { read = input.read(buffer); if (read == -1) { break; } lengthLeft -= read; output.write(buffer, 0, read); } } catch (IOException exp) { NLogger.warn(FileUtils.class, "Third renameTo operation failed."); throw new FileHandlingException(FileHandlingException.RENAME_FAILED, exp); } finally { IOUtil.closeQuietly(input); IOUtil.closeQuietly(output); } //file copy should preserve file date destFile.setLastModified(sourceFile.lastModified()); // try to delete file FileUtils.deleteFileMultiFallback(sourceFile); }
From source file:com.facebook.FileLruCache.java
InputStream get(String key, String contentTag) throws IOException { File file = new File(this.directory, Utility.md5hash(key)); FileInputStream input = null; try {/*from ww w.j ava 2s . co m*/ input = new FileInputStream(file); } catch (IOException e) { return null; } BufferedInputStream buffered = new BufferedInputStream(input, Utility.DEFAULT_STREAM_BUFFER_SIZE); boolean success = false; try { JSONObject header = StreamHeader.readHeader(buffered); if (header == null) { return null; } String foundKey = header.optString(HEADER_CACHEKEY_KEY); if ((foundKey == null) || !foundKey.equals(key)) { return null; } String headerContentTag = header.optString(HEADER_CACHE_CONTENT_TAG_KEY, null); if (headerContentTag != contentTag) { return null; } long accessTime = new Date().getTime(); Logger.log(LoggingBehaviors.CACHE, TAG, "Setting lastModified to " + Long.valueOf(accessTime) + " for " + file.getName()); file.setLastModified(accessTime); success = true; return buffered; } finally { if (!success) { buffered.close(); } } }
From source file:phex.utils.FileUtils.java
/** * This method performce a multi fallback file rename operation to try to * work around the Java problems with rename operations. * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213298 * @throws FileHandlingException /* w w w. j a v a2 s . c o m*/ */ public static void renameFileMultiFallback(File sourceFile, File destFile) throws FileHandlingException { if (destFile.exists()) { // cant rename to file that already exists throw new FileHandlingException(FileHandlingException.FILE_ALREADY_EXISTS); } if (!sourceFile.exists()) { return; } boolean succ = sourceFile.renameTo(destFile); if (succ) { //NLogger.warn( FileUtils.class, "First renameTo operation worked!" ); return; } //NLogger.warn( FileUtils.class, "First renameTo operation failed." ); // Try to run garbage collector to make the file rename operation work System.gc(); // Yield thread and to hope GC kicks in... Thread.yield(); // Try rename again... succ = sourceFile.renameTo(destFile); if (succ) { return; } //NLogger.warn( FileUtils.class, "Second renameTo operation failed." ); // Rename failed again... just perform a slow copy/delete operation FileInputStream input = null; FileOutputStream output = null; try { input = new FileInputStream(sourceFile); output = new FileOutputStream(destFile); long lengthLeft = sourceFile.length(); byte[] buffer = new byte[(int) Math.min(BUFFER_LENGTH, lengthLeft + 1)]; int read; while (lengthLeft > 0) { read = input.read(buffer); if (read == -1) { break; } lengthLeft -= read; output.write(buffer, 0, read); } } catch (IOException exp) { //NLogger.warn( FileUtils.class, "Third renameTo operation failed." ); throw new FileHandlingException(FileHandlingException.RENAME_FAILED, exp); } finally { IOUtil.closeQuietly(input); IOUtil.closeQuietly(output); } //file copy should preserve file date destFile.setLastModified(sourceFile.lastModified()); // try to delete file FileUtils.deleteFileMultiFallback(sourceFile); }
From source file:cn.com.sinosoft.util.io.FileUtils.java
/** * Internal copy file method.//from w w w .jav a 2s .c om * * @param srcFile the validated source file, must not be <code>null</code> * @param destFile the validated destination file, must not be <code>null</code> * @param preserveFileDate whether to preserve the file date * @throws IOException if an error occurs */ private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
From source file:com.otway.picasasync.webclient.PicasawebClient.java
public void setUpdatedDate(AlbumEntry album, final PhotoEntry photoToChange, File localFile) { try {/*from w w w. ja v a2 s . c om*/ final boolean SETUPDATE_WORKS = false; if (SETUPDATE_WORKS) { List<PhotoEntry> photos = getPhotos(album); for (PhotoEntry photo : photos) { if (photo.getGphotoId().equals(photoToChange.getGphotoId())) { DateTime time = new DateTime(localFile.lastModified()); time.setTzShift(0); log.info("Setting Updated from " + photo.getUpdated() + " to " + time); photo.setUpdated(time); photo.update(); break; } } } else { // Since it doesn't work, the only option to avoid unnecessary uploads/downloads // is to set the lastModified file time on the local file. log.info( "Setting local file time to " + photoToChange.getUpdated() + " for " + localFile.getName()); localFile.setLastModified(photoToChange.getUpdated().getValue()); } } catch (Exception ex) { log.error("Unable to change lastUpdate date for " + photoToChange.getTitle().getPlainText()); } }
From source file:com.alu.e3.logger.LogCollector.java
/** * Copies a file on a remote host to a local path. Before copying, renames source file * with a temporary name to move it out of the way of any rotator process. * Optionally deletes the file from the remote host. * //from w ww .ja v a 2s . c om * @param sshCommand An active (connected) SSHCommand * @param remoteFileInfo A FileInfo structure representing the remote file * @param localFilePath The full path for the local file copy * @param deleteSource If <code>true</code> and the copied succeeds, the remote file will be deleted * @return The number of bytes copied. * @throws JSchException * @throws IOException */ private static long copyRemoteFile(SSHCommand sshCommand, FileInfo remoteFileInfo, String localFilePath, boolean deleteSource) throws JSchException, IOException { String remoteFilePath = remoteFileInfo.filePath; String tempRemotePath = tempNameForSourceFile(remoteFilePath); File localFile = null; long bytesCopied = 0L; IOException cleanupIOException = null; JSchException cleanupJSchException = null; boolean success = false; // Copy file and validate result try { // Rename the remote file with a temporary name before copying if (logger.isDebugEnabled()) { logger.debug("Renaming remote file to: {}", tempRemotePath); } sshCommand.execShellCommand("mv " + remoteFilePath + " " + tempRemotePath); // Copy the (renamed) remote file to local destination remoteFileInfo.filePath = tempRemotePath; // remote file name is needed during validation bytesCopied = sshCommand.copyFrom(tempRemotePath, localFilePath); localFile = new File(localFilePath); long modTime = (long) (Double.parseDouble(remoteFileInfo.fileModtime) * 1000.0); localFile.setLastModified(modTime); // Check integrity of copy success = validateRemoteFileCopy(sshCommand, remoteFileInfo, localFilePath); if (!success) { logger.warn("Copy of file {} did not pass integrity check!", remoteFilePath); } } catch (IOException ex) { // If there's been an error copying the file, we may be left with a zero-length or incomplete file if ((localFile != null) && localFile.exists() && !success) { if (logger.isDebugEnabled()) { logger.debug("Deleting failed local copy of remote file: {}", localFile.getAbsolutePath()); } localFile.delete(); } } finally { // Use a try-block during cleanup, but only throw exception if the // main file-copy try-block doesn't try { if (deleteSource && success) { if (logger.isDebugEnabled()) { logger.debug("Deleting remote file: {}", tempRemotePath); } sshCommand.execShellCommand("rm " + tempRemotePath); } else { // Move source file back from temporary name sshCommand.execShellCommand("mv " + tempRemotePath + " " + remoteFilePath); } } catch (JSchException ex) { logger.warn("JSchException during remote file copy cleanup: {}", ex); cleanupJSchException = new JSchException(ex.getMessage()); } catch (IOException ex) { logger.warn("IOException during remote file copy cleanup: {}", ex); cleanupIOException = new IOException(ex); } remoteFileInfo.filePath = remoteFilePath; // restore original file name in argument } if (cleanupJSchException != null) { throw cleanupJSchException; } else if (cleanupIOException != null) { throw cleanupIOException; } return bytesCopied; }
From source file:com.emc.ecs.sync.target.CuaFilesystemTarget.java
@Override public void filter(SyncObject obj) { timeOperationStart(CasUtil.OPERATION_TOTAL); if (!(obj instanceof ClipSyncObject)) throw new UnsupportedOperationException("sync object was not a CAS clip"); final ClipSyncObject clipSync = (ClipSyncObject) obj; try {/*from w ww .ja v a 2 s .com*/ // looking for clips with a specific name if (!clipSync.getClipName().equals(CLIP_NAME)) { log.debug("skipped clip {} (clip name did not match)", clipSync.getRawSourceIdentifier()); } else { ClipTag blobTag = null; String filePath = null; Date itime = null, mtime = null, atime = null; long hi = 0, lo = 0; for (ClipTag clipTag : clipSync.getTags()) { FPTag sourceTag = clipTag.getTag(); if (sourceTag.getTagName().equals(ATTRIBUTE_TAG_NAME)) { // pull all pertinent attributes filePath = sourceTag.getStringAttribute(PATH_ATTRIBUTE); itime = new Date(sourceTag.getLongAttribute(ITIME_ATTRIBUTE) * 1000); // tag value is in seconds mtime = new Date(sourceTag.getLongAttribute(MTIME_ATTRIBUTE) * 1000); // .. convert to ms atime = new Date(sourceTag.getLongAttribute(ATIME_ATTRIBUTE) * 1000); hi = sourceTag.getLongAttribute(SIZE_HI_ATTRIBUTE); lo = sourceTag.getLongAttribute(SIZE_LO_ATTRIBUTE); } else if (sourceTag.getTagName().equals(BLOB_TAG_NAME)) { blobTag = clipTag; } } // sanity check if (blobTag == null) throw new RuntimeException("could not find blob tag"); if (filePath == null) throw new RuntimeException("could not find file path attribute"); // assume the rest have been pulled // make file path relative if (filePath.startsWith("/")) filePath = filePath.substring(1); File destFile = new File(targetDir, filePath); obj.setTargetIdentifier(destFile.getPath()); // transfer the clip if: // - force is enabled // - target does not exist // - source mtime is after target mtime, or // - source size is different from target size long size = (lo > 0 ? hi << 32 : hi) + lo; if (force || !destFile.exists() || mtime.after(new Date(destFile.lastModified())) || size != destFile.length()) { log.info("writing {} to {}", obj.getSourceIdentifier(), destFile); // make parent directories mkdirs(destFile.getParentFile()); // write the file try (OutputStream out = new FileOutputStream(destFile)) { blobTag.writeToStream(out); } // set times log.debug("updating timestamps for {}", destFile.getPath()); Path destPath = destFile.toPath(); Files.setAttribute(destPath, "creationTime", FileTime.fromMillis(itime.getTime())); Files.setAttribute(destPath, "lastModifiedTime", FileTime.fromMillis(mtime.getTime())); Files.setAttribute(destPath, "lastAccessTime", FileTime.fromMillis(atime.getTime())); if (!destFile.setLastModified(mtime.getTime())) log.warn("could not set mtime for {}", destFile.getPath()); // verify size if (size != destFile.length()) throw new RuntimeException(String .format("target file %s is not the right size (expected %d)", destFile, size)); } else { log.info("{} is up to date, skipping", destFile); } } timeOperationComplete(CasUtil.OPERATION_TOTAL); } catch (Throwable t) { timeOperationFailed(CasUtil.OPERATION_TOTAL); if (t instanceof RuntimeException) throw (RuntimeException) t; if (t instanceof FPLibraryException) throw new RuntimeException( "Failed to store object: " + CasUtil.summarizeError((FPLibraryException) t), t); throw new RuntimeException("failed to sync object: " + t.getMessage(), t); } }
From source file:com.dotosoft.dotoquiz.tools.thirdparty.PicasawebClient.java
public void updateTimeFromTags(File localFile, PhotoEntry photo, boolean createdFolder) throws com.google.gdata.util.ParseException, IOException { ExifTags tags = photo.getExifTags(); DateTime photoDate = null;/*from w w w . j a va 2 s. c o m*/ if (tags != null) { Date timestamp = tags.getTime(); if (timestamp != null) photoDate = new DateTime(timestamp); } if (photoDate == null) { photoDate = photo.getUpdated(); } log.debug("Setting datetime for " + localFile.getName() + " to " + photoDate.toString()); Path fp = Paths.get(localFile.getPath()); FileTime time = FileTime.fromMillis(photoDate.getValue()); Files.setAttribute(fp, "basic:creationTime", time); long lastUpdated = photo.getUpdated().getValue(); // Set the last update time of the local file... log.debug("Setting last update datetime for " + localFile.getName() + " to " + photo.getUpdated()); if (!localFile.setLastModified(lastUpdated)) log.warn("Unable to set date/time stamp for file: " + localFile); }
From source file:com.google.gwt.dev.shell.tomcat.EmbeddedTomcatServer.java
private void copyFileNoOverwrite(TreeLogger logger, String srcResName, Resource srcRes, File catBase) { File dest = new File(catBase, srcResName); try {//from w w w .j ava 2 s. c o m // Only copy if src is newer than desc. long srcLastModified = srcRes.getLastModified(); long dstLastModified = dest.lastModified(); if (srcLastModified < dstLastModified) { // Don't copy over it. if (logger.isLoggable(TreeLogger.SPAM)) { logger.log(TreeLogger.SPAM, "Source is older than existing: " + dest.getAbsolutePath(), null); } return; } else if (srcLastModified == dstLastModified) { // Exact same time; quietly don't overwrite. return; } else if (dest.exists()) { // Warn about the overwrite logger.log(TreeLogger.WARN, "Overwriting existing file '" + dest.getAbsolutePath() + "' with '" + srcRes.getLocation() + "', which has a newer timestamp"); } // Make dest directories as required. File destParent = dest.getParentFile(); if (destParent != null) { // No need to check mkdirs result because IOException later anyway. destParent.mkdirs(); } Util.copy(srcRes.openContents(), new FileOutputStream(dest)); dest.setLastModified(srcLastModified); if (logger.isLoggable(TreeLogger.TRACE)) { logger.log(TreeLogger.TRACE, "Wrote: " + dest.getAbsolutePath(), null); } } catch (IOException e) { logger.log(TreeLogger.WARN, "Failed to write: " + dest.getAbsolutePath(), e); } }