下面列出了java.io.File#setLastModified ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Saves passed output string to cache file and sets the same modification time as routes.rb has.
*
* @param output String that contains stdout of 'rake routes' command.
*/
private void cacheOutput(String output) {
try {
String fileName = getCacheFileName();
if (fileName == null)
return;
// Cache output
File f = new File(fileName);
FileUtil.writeToFile(f, output.getBytes(), false);
// Set cache file modification date/time the same as for routes.rb
f.setLastModified(getRoutesFilesMTime());
} catch (Exception e) {
// Do nothing
}
}
@Test
public void testMissingFileDoesNotThrow() throws Exception {
assertTrue(spoolDir.mkdirs());
File logFile2 = new File(spoolDir, "x2.log").getAbsoluteFile();
new FileWriter(logFile2).close();
logFile2.setLastModified(System.currentTimeMillis() - 10000);
File logFile3 = new File(spoolDir, "x3.log").getAbsoluteFile();
new FileWriter(logFile3).close();
logFile2.setLastModified(System.currentTimeMillis() - 9000);
DirectorySpooler.Builder builder = initializeAndGetBuilder()
.setUseLastModifiedTimestamp(true)
.setMaxSpoolFiles(3);
DirectorySpooler spooler = builder.build();
Assert.assertEquals(2, spoolDir.list().length);
assertTrue(logFile2.exists());
assertTrue(logFile3.exists());
spooler.init("x1.log");
Assert.assertEquals(logFile2.getAbsolutePath(), spooler.poolForFile(intervalMillis, TimeUnit.MILLISECONDS).getAbsolutePath());
Assert.assertEquals(logFile3.getAbsolutePath(), spooler.poolForFile(intervalMillis, TimeUnit.MILLISECONDS).getAbsolutePath());
Assert.assertNull(spooler.poolForFile(intervalMillis, TimeUnit.MILLISECONDS));
spooler.destroy();
}
/**
* 保存Resource到持久化,这个实现中是文件
*
* @param mediaEntity
* @return File
*/
@Override
public Resource storeResource(MediaEntity mediaEntity) throws IOException {
if (!(mediaEntity.getResource() instanceof WxMediaResource)) {
return null;
}
WxMediaResource wxMediaResource = (WxMediaResource) mediaEntity.getResource();
if (wxMediaResource.isUrlMedia()) {
return null;
}
String fileName = wxMediaResource.getFilename();
if (fileName == null) {
fileName = mediaEntity.getMediaId();
}
File file = new File(StringUtils.applyRelativePath(Type.TEMP.equals(mediaEntity.getStoreType()) ? defaultTempFilePath : defaultFilePath, fileName));
if (file.exists()) {
return new FileSystemResource(file);
}
file.createNewFile();
file.setLastModified(System.currentTimeMillis());
FileCopyUtils.copy(mediaEntity.getResource().getInputStream(), new FileOutputStream(file));
mediaEntity.setResourcePath(file.getAbsolutePath());
store(mediaEntity);
return new FileSystemResource(file);
}
@Test
public void preservesModifiedDate() throws Exception {
File playground = emptyVMDirectory("totallylazy");
File a = file(playground, "a.txt");
Date date = date(2001, 1, 10);
a.setLastModified(date.getTime());
File zipFile = temporaryFile();
Zip.zip(playground, zipFile);
Files.deleteFiles(playground);
Zip.unzip(zipFile, playground);
assertThat(a.exists(), is(true));
assertThat(new Date(a.lastModified()), is(date));
Files.deleteFiles(playground);
zipFile.delete();
}
/**
* Modify the listenerProfiles.xml file after modifying the certificate.
*
* @return : True if the file modification is success.
*/
private boolean touchSSLListenerConfigFile() {
boolean success = false;
if (listenerProfileFilePath != null) {
File file = new File(listenerProfileFilePath);
if (file.exists()) {
success = file.setLastModified(System.currentTimeMillis());
if (success) {
log.info("The Transport listener will be re-initialized in few minutes.");
} else {
if (log.isDebugEnabled()) {
log.debug(
"Error when modifying listener profile config file in path " + listenerProfileFilePath);
}
log.error("Could not modify the file listener profile config file");
}
}
} else {
log.warn("Mutual SSL file path for listener is not configured correctly in axis2.xml. Please recheck the "
+ "relevant configuration under transport listener.");
}
return success;
}
@Test
public void testPicksUpNewFiles() throws Exception {
String originPath =
currentThread().getContextClassLoader().getResource("remote-download-source/parseNoError").getPath();
File originDirFile = new File(originPath).listFiles()[0];
File tempDir = testFolder.newFolder();
File copied = new File(tempDir, originDirFile.getName());
Files.copy(originDirFile, copied);
long lastModified = copied.lastModified();
setupServer(tempDir.toString(), true);
RemoteDownloadSource origin = new TestRemoteDownloadSourceBuilder(scheme, port).build();
SourceRunner runner = new SourceRunner.Builder(RemoteDownloadDSource.class, origin)
.addOutputLane("lane")
.build();
runner.runInit();
String offset = RemoteDownloadSource.NOTHING_READ;
StageRunner.Output op = runner.runProduce(offset, 1000);
offset = op.getNewOffset();
List<Record> expected = getExpectedRecords();
List<Record> actual = op.getRecords().get("lane");
Assert.assertEquals(expected.size(), actual.size());
for (int i = 0; i < 2; i++) {
Assert.assertEquals(expected.get(i).get(), actual.get(i).get());
}
File eventualFile = new File(tempDir, "z" + originDirFile.getName());
Files.copy(originDirFile, eventualFile);
eventualFile.setLastModified(lastModified);
op = runner.runProduce(offset, 1000);
expected = getExpectedRecords();
actual = op.getRecords().get("lane");
Assert.assertEquals(expected.size(), actual.size());
for (int i = 0; i < 2; i++) {
Assert.assertEquals(expected.get(i).get(), actual.get(i).get());
}
destroyAndValidate(runner);
}
/**
* Internal copy directory method.
*
* @param srcDir the validated source directory, must not be {@code null}
* @param destDir the validated destination directory, must not be {@code null}
* @param filter the filter to apply, null means copy all directories and files
* @param preserveFileDate whether to preserve the file date
* @param exclusionList List of files and directories to exclude from the copy, may be null
* @throws IOException if an error occurs
* @since 1.1
*/
private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter,
boolean preserveFileDate, List<String> exclusionList) throws IOException {
// recurse
File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if (srcFiles == null) { // null if abstract pathname does not denote a directory, or if an I/O error occurs
throw new IOException("Failed to list contents of " + srcDir);
}
if (destDir.exists()) {
if (destDir.isDirectory() == false) {
throw new IOException("Destination '" + destDir + "' exists but is not a directory");
}
} else {
if (!destDir.mkdirs() && !destDir.isDirectory()) {
throw new IOException("Destination '" + destDir + "' directory cannot be created");
}
}
if (destDir.canWrite() == false) {
throw new IOException("Destination '" + destDir + "' cannot be written to");
}
for (File srcFile : srcFiles) {
File dstFile = new File(destDir, srcFile.getName());
if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) {
if (srcFile.isDirectory()) {
doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList);
} else {
doCopyFile(srcFile, dstFile, preserveFileDate);
}
}
}
// Do this last, as the above has probably affected directory metadata
if (preserveFileDate) {
destDir.setLastModified(srcDir.lastModified());
}
}
public static void setLastModifiedNow(File file) throws IOException {
if (file.exists()) {
long now = System.currentTimeMillis();
boolean modified = file.setLastModified(now); // on some devices (e.g. Nexus 5) doesn't work
if (!modified) {
modify(file);
}
}
}
public static boolean touch(File file) {
try {
if (!file.exists()) {
new FileOutputStream(file).close();
}
return file.setLastModified(System.currentTimeMillis());
} catch (IOException e) {
return false;
}
}
/***/
protected void replaceFileContentAndWaitForRefresh(IFolder folder, IFile file, String newContent, long newTimestamp)
throws CoreException, IOException {
File fileInFilesystem = file.getLocation().toFile();
FileWriter fileWriter = new FileWriter(fileInFilesystem);
fileWriter.write(newContent);
fileWriter.close();
// We need to update the time of the file since out-of-sync is detected by timestamp on (most) OS
fileInFilesystem.setLastModified(newTimestamp * 1000);
folder.refreshLocal(IResource.DEPTH_INFINITE, monitor());
waitForAutoBuild();
}
private File get(String key) {
File file = newFile(key);
Long currentTime = System.currentTimeMillis();
file.setLastModified(currentTime);
lastUsageDates.put(file, currentTime);
return file;
}
public static void reloadApplication(String buildPath) {
File check = new File(buildPath, RELOAD_FILE);
if (check.exists()) {
check.setLastModified(System.currentTimeMillis());
} else {
try {
check.createNewFile();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
}
@Test
public void shouldDeleteLocalStoreWhenLastModifiedTimeOfOffsetFileIsGreaterThanOffsetTTL() throws Exception {
File offsetFile = createOffsetFile(taskStoreDir);
offsetFile.setLastModified(0);
localStoreMonitor.monitor();
assertTrue("Offset file should not exist.", !offsetFile.exists());
assertEquals(0, localStoreMonitorMetrics.diskSpaceFreedInBytes.getCount());
}
private File get(String key) {
File file = newFile(key);
Long currentTime = System.currentTimeMillis();
file.setLastModified(currentTime);
lastUsageDates.put(file, currentTime);
return file;
}
private static void setFileLastModifiedTime(FileHeader fileHeader, File file) throws ZipException {
if (fileHeader.getLastModFileTime() <= 0) {
return;
}
if (file.exists()) {
file.setLastModified(Zip4jUtil.dosToJavaTme(fileHeader.getLastModFileTime()));
}
}
private static void unzip(final InputStream read, final File destination, final boolean noparent,
final ProgressIndicator indicator) throws IOException {
try (final ZipInputStream in = new ZipInputStream(read)) {
ZipEntry entry;
while ((entry = in.getNextEntry()) != null) {
String path = entry.getName();
if (noparent) {
path = path.replaceFirst("^[^/]+/", "");
}
final File file = new File(destination, path);
if (!file.getCanonicalPath().startsWith(destination.getCanonicalPath())) {
throw new IOException("The output file is not contained in the destination directory");
}
if (entry.isDirectory()) {
indicator.setText("Creating directory " + file.getName());
file.mkdirs();
continue;
}
file.getParentFile().mkdirs();
indicator.setText("Creating file " + file.getName());
Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
final long lastModified = entry.getTime();
if (lastModified > 0) {
file.setLastModified(lastModified);
}
}
} catch (final IOException e) {
throw new IOException("Unable to unzip " + read, e);
}
}
/**
* Test that fileChange event from FileObject.refresh in DES.Env.getTime is ignored
* ie. no property change event from DES.Env is fired.
*/
public void testRename () throws IOException {
counter = 0;
FileObject folder = FileUtil.toFileObject(getWorkDir());
FileObject fo = FileUtil.createData(folder,"someFile.obj");
DataObject obj = DataObject.find(fo);
assertEquals( MyDataObject.class, obj.getClass());
assertTrue( "we need UniFileLoader", obj.getLoader() instanceof UniFileLoader );
EditorCookie ec = obj.getCookie(EditorCookie.class);
DataEditorSupport des = (DataEditorSupport) ec;
DataEditorSupport.Env env = (DataEditorSupport.Env) des.desEnv();
File file = FileUtil.toFile(fo);
//Set lastModified time to future so openDocument -> getTime -> FileObject.refresh
//will generate fileChange event. fileChange event must be ignored in DES.Env to avoid
//firing propertyChange event.
file.setLastModified(file.lastModified() + 1000000L);
env.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
counter++;
}
});
StyledDocument doc = ec.openDocument();
assertEquals("Counter must be zero", 0, counter);
}
private void createLogFile(final String name, final long minutesOld) throws IOException {
File file = new File(temporaryWorkDirectory.getRoot(), name);
file.createNewFile();
file.setLastModified(ZonedDateTime.now().minusMinutes(minutesOld).toInstant().toEpochMilli());
}
private void updateLastModifiedForCache(File f) {
f.setLastModified(System.currentTimeMillis());
}
/**
* Compute diffs for all RD5 files
*/
public static void calcDiffs( File oldDir, File newDir ) throws Exception
{
File oldDiffDir = new File( oldDir, "diff" );
File newDiffDir = new File( newDir, "diff" );
File[] filesNew = newDir.listFiles();
for( File fn : filesNew )
{
String name = fn.getName();
if ( !name.endsWith( ".rd5" ) )
{
continue;
}
if ( fn.length() < 1024*1024 )
{
continue; // exclude very small files from diffing
}
String basename = name.substring( 0, name.length() - 4 );
File fo = new File( oldDir, name );
if ( !fo.isFile() )
{
continue;
}
// calculate MD5 of old file
String md5 = getMD5( fo );
String md5New = getMD5( fn );
System.out.println( "name=" + name + " md5=" + md5 );
File specificNewDiffs = new File( newDiffDir, basename );
specificNewDiffs.mkdirs();
String diffFileName = md5 + ".rd5diff";
File diffFile = new File( specificNewDiffs, diffFileName );
String dummyDiffFileName = md5New + ".rd5diff";
File dummyDiffFile = new File( specificNewDiffs, dummyDiffFileName );
dummyDiffFile.createNewFile();
// calc the new diff
Rd5DiffTool.diff2files( fo, fn, diffFile );
// ... and add that to old diff files
File specificOldDiffs = new File( oldDiffDir, basename );
if ( specificOldDiffs.isDirectory() )
{
File[] oldDiffs = specificOldDiffs.listFiles();
for( File od : oldDiffs )
{
if ( !od.getName().endsWith( ".rd5diff" ) )
{
continue;
}
if ( System.currentTimeMillis() - od.lastModified() > 9*86400000L )
{
continue; // limit diff history to 9 days
}
File updatedDiff = new File( specificNewDiffs, od.getName() );
if ( !updatedDiff.exists() )
{
Rd5DiffTool.addDeltas( od, diffFile, updatedDiff );
updatedDiff.setLastModified( od.lastModified() );
}
}
}
}
}