Java Code Examples for java.io.File#setLastModified()

The following examples show how to use java.io.File#setLastModified() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CertificateManagerImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source File: RoutesManager.java    From railways with MIT License 6 votes vote down vote up
/**
 * 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
    }
}
 
Example 3
Source File: TestDirectorySpooler.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 4
Source File: ZipTest.java    From totallylazy with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 5
Source File: MapDbWxMediaStore.java    From FastBootWeixin with Apache License 2.0 6 votes vote down vote up
/**
 * 保存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);
}
 
Example 6
Source File: AbstractBuilderParticipantTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/***/
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();
}
 
Example 7
Source File: PropertyChangeTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 8
Source File: ProjectDownloader.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 9
Source File: UnzipUtil.java    From AndroidZip with Apache License 2.0 5 votes vote down vote up
private static void setFileLastModifiedTime(FileHeader fileHeader, File file) throws ZipException {
	if (fileHeader.getLastModFileTime() <= 0) {
		return;
	}
	
	if (file.exists()) {
		file.setLastModified(Zip4jUtil.dosToJavaTme(fileHeader.getLastModFileTime()));
	}
}
 
Example 10
Source File: ACache.java    From gank.io-unofficial-android-client with Apache License 2.0 5 votes vote down vote up
private File get(String key) {
  File file = newFile(key);
  Long currentTime = System.currentTimeMillis();
  file.setLastModified(currentTime);
  lastUsageDates.put(file, currentTime);

  return file;
}
 
Example 11
Source File: TestLocalStoreMonitor.java    From samza with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 12
Source File: ReloadAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 13
Source File: ACache.java    From BookReader with Apache License 2.0 5 votes vote down vote up
private File get(String key) {
    File file = newFile(key);
    Long currentTime = System.currentTimeMillis();
    file.setLastModified(currentTime);
    lastUsageDates.put(file, currentTime);

    return file;
}
 
Example 14
Source File: FileUtils.java    From openlauncher with Apache License 2.0 5 votes vote down vote up
public static boolean touch(File file) {
    try {
        if (!file.exists()) {
            new FileOutputStream(file).close();
        }
        return file.setLastModified(System.currentTimeMillis());
    } catch (IOException e) {
        return false;
    }
}
 
Example 15
Source File: LocalProxyUtils.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 16
Source File: FileUtils.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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());
    }
}
 
Example 17
Source File: TestRemoteDownloadSource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 18
Source File: TaskLogCustomizerTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
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());
}
 
Example 19
Source File: Rd5DiffManager.java    From brouter with MIT License 4 votes vote down vote up
/**
 * 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() );
        }
      }
    }
  }
}
 
Example 20
Source File: BitmapUtil.java    From Yahala-Messenger with MIT License 4 votes vote down vote up
private void updateLastModifiedForCache(File f) {
    f.setLastModified(System.currentTimeMillis());
}