java.io.File.setLastModified()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(10.0k)|赞(0)|评价(0)|浏览(242)

本文整理了Java中java.io.File.setLastModified()方法的一些代码示例,展示了File.setLastModified()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。File.setLastModified()方法的具体详情如下:
包路径:java.io.File
类名称:File
方法名:setLastModified

File.setLastModified介绍

[英]Sets the time this file was last modified, measured in milliseconds since January 1st, 1970, midnight.

Note that this method does not throw IOException on failure. Callers must check the return value.
[中]设置上次修改此文件的时间,自1970年1月1日午夜起以毫秒为单位。
请注意,此方法不会在失败时引发IOException。调用者必须检查返回值。

代码示例

代码示例来源:origin: google/guava

/**
 * Creates an empty file or updates the last updated timestamp on the same as the unix command of
 * the same name.
 *
 * @param file the file to create or update
 * @throws IOException if an I/O error occurs
 */
@SuppressWarnings("GoodTime") // reading system time without TimeSource
public static void touch(File file) throws IOException {
 checkNotNull(file);
 if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) {
  throw new IOException("Unable to update modification time of " + file);
 }
}

代码示例来源:origin: jenkinsci/jenkins

@Override
    public Void invoke(File f, VirtualChannel channel) throws IOException {
      if(!f.exists()) {
        Files.newOutputStream(fileToPath(creating(f))).close();
      }
      if(!stating(f).setLastModified(timestamp))
        throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp);
      return null;
    }
}

代码示例来源:origin: redisson/redisson

/**
 * Implements the Unix "touch" utility. It creates a new file
 * with size 0 or, if the file exists already, it is opened and
 * closed without modifying it, but updating the file date and time.
 */
public static void touch(File file) throws IOException {
  if (!file.exists()) {
    StreamUtil.close(new FileOutputStream(file));
  }
  file.setLastModified(System.currentTimeMillis());
}

代码示例来源:origin: commons-io/commons-io

if (destFile.exists() && destFile.isDirectory()) {
  throw new IOException("Destination '" + destFile + "' exists but is a directory");
   FileOutputStream fos = new FileOutputStream(destFile);
   FileChannel output = fos.getChannel()) {
  final long size = input.size(); // TODO See IO-386
final long dstLen = destFile.length(); // TODO See IO-386
if (srcLen != dstLen) {
  throw new IOException("Failed to copy full contents from '" +
      srcFile + "' to '" + destFile + "' Expected length: " + srcLen + " Actual: " + dstLen);
  destFile.setLastModified(srcFile.lastModified());

代码示例来源:origin: jphp-group/jphp

public static boolean touch(Environment env, TraceInfo trace, String path, long time, long atime) {
  File file = new File(path);
  if (!file.exists())
    try {
      if (!file.createNewFile())
        return false;
    } catch (IOException e) {
      env.warning(trace, e.getMessage());
      return false;
    }
  return file.setLastModified(time * 1000);
}

代码示例来源:origin: spotbugs/spotbugs

public void testFilesMethods() throws IOException {
    File f = new File("blah.txt");
    File f2 = new File("blah2.txt");

    // All of these should generate a warning
    f.mkdir();
    f.mkdirs();
    f.delete();
    f.createNewFile();
    f.setLastModified(1L);
    f.setReadOnly();
    f.renameTo(f2);
  }
}

代码示例来源:origin: org.apache.hadoop/hadoop-common

entry = zip.getNextEntry()) {
if (!entry.isDirectory()) {
 File file = new File(toDir, entry.getName());
 if (!file.getCanonicalPath().startsWith(targetDirPath)) {
  throw new IOException("expanding " + entry.getName()
    + " would create file outside of " + toDir);
 if (!parent.mkdirs() &&
   !parent.isDirectory()) {
  throw new IOException("Mkdirs failed to create " +
    parent.getAbsolutePath());
 try (OutputStream out = new FileOutputStream(file)) {
  IOUtils.copyBytes(zip, out, BUFFER_SIZE);
 if (!file.setLastModified(entry.getTime())) {
  numOfFailedLastModifiedSet++;

代码示例来源:origin: apache/flink

while ((entry = jis.getNextJarEntry()) != null) {
  if (entry.isDirectory()) {
    File dir = new File(destDir, entry.getName());
    dir.mkdir();
    if (entry.getTime() != -1) {
      dir.setLastModified(entry.getTime());
  File destFile = new File(destDir, entry.getName());
  if (mVerbose) {
    System.out.println("unjarring " + destFile +
      " from " + entry.getName());
  FileOutputStream fos = new FileOutputStream(destFile);
  dest = new BufferedOutputStream(fos, BUFFER_SIZE);
  try {
    destFile.setLastModified(entry.getTime());

代码示例来源:origin: apache/incubator-gobblin

File file = new File(PathUtils.getPathWithoutSchemeAndAuthority(fullFilePath).toString());
boolean modifiedFile =
  file.setLastModified(FORMATTER.parseMillis(fileToCreate.getString(TEST_DATA_MOD_TIME_LOCAL_KEY)));
if (!modifiedFile) {
 throw new IOException(String.format("Unable to set the last modified time for file %s!", file));

代码示例来源:origin: alibaba/jstorm

public static void main(String[] args) {
  long current_time = System.currentTimeMillis();
  String test = "test";
  File file = new File(test);
  file.delete();
  file.mkdir();
  file.setLastModified(current_time);
  JStormUtils.sleepMs(10 * 1000);
  File newFile = new File(test);
  System.out.println("modify time: " + newFile.lastModified() + ", raw:" + current_time);
}

代码示例来源:origin: CarGuo/GSYVideoPlayer

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);
      if (file.lastModified() < now) {
        // NOTE: apparently this is a known issue (see: http://stackoverflow.com/questions/6633748/file-lastmodified-is-never-what-was-set-with-file-setlastmodified)
        HttpProxyCacheDebuger.printfWarning("Last modified date {} is not set for file {}", new Date(file.lastModified()).toString() + "\n" + file.getAbsolutePath());
      }
    }
  }
}

代码示例来源:origin: twitter/distributedlog

public void save() throws Exception {
  FileOutputStream outputStream = new FileOutputStream(configFile);
  properties.store(outputStream, null);
  configFile.setLastModified(configFile.lastModified()+1000);
  LOG.debug("save modified={}", configFile.lastModified());
}

代码示例来源:origin: jmxtrans/jmxtrans

private static void touch(File file) throws IOException {
  new FileOutputStream(file, true).close(); // ensure file exists and it's accessible
  assert(file.setLastModified(System.currentTimeMillis()));
}

代码示例来源:origin: org.netbeans.api/org-openide-filesystems

@Override
  public void close() throws IOException {
    super.close();
    if ((f.length() == 0) && (f.lastModified() == lModified)) {
      f.setLastModified(System.currentTimeMillis());
    }
  }
};

代码示例来源:origin: jenkinsci/jenkins

/**
 * Copies the bundled plugin from the given URL to the destination of the given file name (like 'abc.jpi'),
 * with a reasonable up-to-date check. A convenience method to be used by the {@link #loadBundledPlugins()}.
 */
protected void copyBundledPlugin(URL src, String fileName) throws IOException {
  LOGGER.log(FINE, "Copying {0}", src);
  fileName = fileName.replace(".hpi",".jpi"); // normalize fileNames to have the correct suffix
  String legacyName = fileName.replace(".jpi",".hpi");
  long lastModified = getModificationDate(src);
  File file = new File(rootDir, fileName);
  // normalization first, if the old file exists.
  rename(new File(rootDir,legacyName),file);
  // update file if:
  //  - no file exists today
  //  - bundled version and current version differs (by timestamp).
  if (!file.exists() || file.lastModified() != lastModified) {
    FileUtils.copyURLToFile(src, file);
    file.setLastModified(getModificationDate(src));
    // lastModified is set for two reasons:
    // - to avoid unpacking as much as possible, but still do it on both upgrade and downgrade
    // - to make sure the value is not changed after each restart, so we can avoid
    // unpacking the plugin itself in ClassicPluginStrategy.explode
  }
  // Plugin pinning has been deprecated.
  // See https://groups.google.com/d/msg/jenkinsci-dev/kRobm-cxFw8/6V66uhibAwAJ
}

代码示例来源:origin: oracle/opengrok

public void stamp() throws IOException {
    RuntimeEnvironment env = RuntimeEnvironment.getInstance();
    File timestamp = new File(env.getDataRootFile(), "timestamp");
    String purpose = "used for timestamping the index database.";
    if (timestamp.exists()) {
      if (!timestamp.setLastModified(System.currentTimeMillis())) {
        LOGGER.log(Level.WARNING, "Failed to set last modified time on ''{0}'', {1}",
          new Object[]{timestamp.getAbsolutePath(), purpose});
      }
    } else {
      if (!timestamp.createNewFile()) {
        LOGGER.log(Level.WARNING, "Failed to create file ''{0}'', {1}",
          new Object[]{timestamp.getAbsolutePath(), purpose});
      }
    }
  }
}

代码示例来源:origin: apache/incubator-pinot

@Override
public boolean touch(URI uri)
  throws IOException {
 File file = new File(decodeURI(uri.getRawPath()));
 if (!exists(uri)) {
  return file.createNewFile();
 }
 return file.setLastModified(System.currentTimeMillis());
}

代码示例来源:origin: org.apache.hadoop/hadoop-common

unpackRegex.matcher(entry.getName()).matches()) {
try (InputStream in = jar.getInputStream(entry)) {
 File file = new File(toDir, entry.getName());
 if (!file.getCanonicalPath().startsWith(targetDirPath)) {
  throw new IOException("expanding " + entry.getName()
    + " would create file outside of " + toDir);
 try (OutputStream out = new FileOutputStream(file)) {
  IOUtils.copyBytes(in, out, BUFFER_SIZE);
 if (!file.setLastModified(entry.getTime())) {
  numOfFailedLastModifiedSet++;

代码示例来源:origin: apache/incubator-gobblin

@Test
public void testPurge() throws Exception {
 String content = "contents";
 File persistDirBase = Files.createTempDir();
 persistDirBase.deleteOnExit();
 State state = new State();
 state.setProp(RecoveryHelper.PERSIST_DIR_KEY, persistDirBase.getAbsolutePath());
 state.setProp(RecoveryHelper.PERSIST_RETENTION_KEY, "1");
 RecoveryHelper recoveryHelper = new RecoveryHelper(FileSystem.getLocal(new Configuration()), state);
 File persistDir = new File(RecoveryHelper.getPersistDir(state).get().toString());
 persistDir.mkdir();
 File file = new File(persistDir, "file1");
 OutputStream os = new FileOutputStream(file);
 IOUtils.write(content, os);
 os.close();
 file.setLastModified(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(2));
 File file2 = new File(persistDir, "file2");
 OutputStream os2 = new FileOutputStream(file2);
 IOUtils.write(content, os2);
 os2.close();
 Assert.assertEquals(persistDir.listFiles().length, 2);
 recoveryHelper.purgeOldPersistedFile();
 Assert.assertEquals(persistDir.listFiles().length, 1);
}

代码示例来源:origin: jenkinsci/jenkins

while (entries.hasMoreElements()) {
  ZipEntry e = entries.nextElement();
  File f = new File(dir, e.getName());
  if (!f.toPath().normalize().startsWith(dir.toPath())) {
    throw new IOException(
      "Zip " + zipFile.getPath() + " contains illegal file name that breaks out of the target directory: " + e.getName());
      LOGGER.log(Level.WARNING, "unable to set permissions", ex);
    f.setLastModified(e.getTime());

相关文章