Java Code Examples for java.nio.file.attribute.FileTime#toMillis()

The following examples show how to use java.nio.file.attribute.FileTime#toMillis() . 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: SymbolicLinkHelper.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the last modified time for a symbolic link.
 *
 * Note: symbolic links are not followed (NOFOLLOW_LINKS LinkOption)
 *
 * @param link the path to the symbolic link
 * @return last modified time of the symbolic link
 */
public static long getLastModifiedTime(String link) {
  if (nonNull(link)) {
    try {
      Path linkPath = Paths.get(link);
      if (nonNull(linkPath)) {
        FileTime fileTimeObject = Files.getLastModifiedTime(linkPath, LinkOption.NOFOLLOW_LINKS);
        if (nonNull(fileTimeObject)) {
          return fileTimeObject.toMillis();
        }
      }
    } catch (Throwable thr) {
      Log.error("Unexpected exception invoking method: %s", thr.getLocalizedMessage());
      Log.exception(thr);
    }
  }
  return 0L;
}
 
Example 2
Source File: TestExtraTime.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void testTimeConversions(long from, long to, long step) {
    ZipEntry ze = new ZipEntry("TestExtraTime.java");
    for (long time = from; time <= to; time += step) {
        ze.setTime(time);
        FileTime lastModifiedTime = ze.getLastModifiedTime();
        if (lastModifiedTime.toMillis() != time) {
            throw new RuntimeException("setTime should make getLastModifiedTime " +
                    "return the specified instant: " + time +
                    " got: " + lastModifiedTime.toMillis());
        }
        if (ze.getTime() != time) {
            throw new RuntimeException("getTime after setTime, expected: " +
                    time + " got: " + ze.getTime());
        }
    }
}
 
Example 3
Source File: FileDataStorageManager.java    From herddb with Apache License 2.0 6 votes vote down vote up
private Path getMostRecentCheckPointFile(Path dir) throws IOException {
    Path result = null;
    long lastMod = -1;
    Files.createDirectories(dir);
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path path : stream) {
            if (isTableOrIndexCheckpointsFile(path)) {
                LOGGER.log(Level.FINER, "getMostRecentCheckPointFile on " + dir.toAbsolutePath() + " -> ACCEPT " + path);
                FileTime lastModifiedTime = Files.getLastModifiedTime(path);
                long ts = lastModifiedTime.toMillis();
                if (lastMod < 0 || lastMod < ts) {
                    result = path;
                    lastMod = ts;
                }
            } else {
                LOGGER.log(Level.FINER, "getMostRecentCheckPointFile on " + dir.toAbsolutePath() + " -> SKIP " + path);
            }
        }
    }
    LOGGER.log(Level.FINER, "getMostRecentCheckPointFile on " + dir.toAbsolutePath() + " -> " + result);
    return result;
}
 
Example 4
Source File: TestExtraTime.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
static void testTimeConversions(long from, long to, long step) {
    ZipEntry ze = new ZipEntry("TestExtraTime.java");
    for (long time = from; time <= to; time += step) {
        ze.setTime(time);
        FileTime lastModifiedTime = ze.getLastModifiedTime();
        if (lastModifiedTime.toMillis() != time) {
            throw new RuntimeException("setTime should make getLastModifiedTime " +
                    "return the specified instant: " + time +
                    " got: " + lastModifiedTime.toMillis());
        }
        if (ze.getTime() != time) {
            throw new RuntimeException("getTime after setTime, expected: " +
                    time + " got: " + ze.getTime());
        }
    }
}
 
Example 5
Source File: HadoopFileSystem.java    From jsr203-hadoop with Apache License 2.0 6 votes vote down vote up
public void setTimes(byte[] bs, FileTime mtime, FileTime atime, FileTime ctime) throws IOException
{
	org.apache.hadoop.fs.Path hp = new HadoopPath(this, bs).getRawResolvedPath();
	long mtime_millis = 0;
	long atime_millis = 0;
   // Get actual value
	if (mtime == null || atime == null)
	{
		FileStatus stat = this.fs.getFileStatus(hp);
     mtime_millis = stat.getModificationTime();
		atime_millis = stat.getAccessTime();
	}
   if (mtime != null) {
     mtime_millis = mtime.toMillis();
   }
   if (atime != null) {
     atime_millis = atime.toMillis();
   }
	this.fs.setTimes(hp, mtime_millis, atime_millis);
}
 
Example 6
Source File: TestExtraTime.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static void testTimeConversions(long from, long to, long step) {
    ZipEntry ze = new ZipEntry("TestExtraTime.java");
    for (long time = from; time <= to; time += step) {
        ze.setTime(time);
        FileTime lastModifiedTime = ze.getLastModifiedTime();
        if (lastModifiedTime.toMillis() != time) {
            throw new RuntimeException("setTime should make getLastModifiedTime " +
                    "return the specified instant: " + time +
                    " got: " + lastModifiedTime.toMillis());
        }
        if (ze.getTime() != time) {
            throw new RuntimeException("getTime after setTime, expected: " +
                    time + " got: " + ze.getTime());
        }
    }
}
 
Example 7
Source File: RollingFileManager.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static long initialFileTime(File file) {
    Path path = file.toPath();
    if (Files.exists(path)) {
        try {
            BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
            FileTime fileTime = attrs.creationTime();
            if (fileTime.compareTo(EPOCH) > 0) {
                return fileTime.toMillis();
            }
            LOGGER.info("Unable to obtain file creation time for " + file.getAbsolutePath());
        } catch (Exception ex) {
            LOGGER.info("Unable to calculate file creation time for " + file.getAbsolutePath() + ": " + ex.getMessage());
        }
    }
    return file.lastModified();
}
 
Example 8
Source File: TestExtraTime.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
static void testTimeConversions(long from, long to, long step) {
    ZipEntry ze = new ZipEntry("TestExtraTime.java");
    for (long time = from; time <= to; time += step) {
        ze.setTime(time);
        FileTime lastModifiedTime = ze.getLastModifiedTime();
        if (lastModifiedTime.toMillis() != time) {
            throw new RuntimeException("setTime should make getLastModifiedTime " +
                    "return the specified instant: " + time +
                    " got: " + lastModifiedTime.toMillis());
        }
        if (ze.getTime() != time) {
            throw new RuntimeException("getTime after setTime, expected: " +
                    time + " got: " + ze.getTime());
        }
    }
}
 
Example 9
Source File: TestExtraTime.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void testTimeConversions(long from, long to, long step) {
    ZipEntry ze = new ZipEntry("TestExtraTime.java");
    for (long time = from; time <= to; time += step) {
        ze.setTime(time);
        FileTime lastModifiedTime = ze.getLastModifiedTime();
        if (lastModifiedTime.toMillis() != time) {
            throw new RuntimeException("setTime should make getLastModifiedTime " +
                    "return the specified instant: " + time +
                    " got: " + lastModifiedTime.toMillis());
        }
        if (ze.getTime() != time) {
            throw new RuntimeException("getTime after setTime, expected: " +
                    time + " got: " + ze.getTime());
        }
    }
}
 
Example 10
Source File: SymbolicLinkHelper.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the last modified time for a symbolic link.
 *
 * Note: symbolic links are not followed (NOFOLLOW_LINKS LinkOption)
 *
 * @param link the path to the symbolic link
 * @return last modified time of the symbolic link
 */
public static long getLastModifiedTime(String link) {
  if (nonNull(link)) {
    try {
      Path linkPath = Paths.get(link);
      if (nonNull(linkPath)) {
        FileTime fileTimeObject = Files.getLastModifiedTime(linkPath, LinkOption.NOFOLLOW_LINKS);
        if (nonNull(fileTimeObject)) {
          return fileTimeObject.toMillis();
        }
      }
    // p4ic4idea: Do not catch throwable unless you're really careful
    //} catch (Throwable thr) {
    } catch (Exception thr) {
      Log.error("Unexpected exception invoking method: %s", thr.getLocalizedMessage());
      Log.exception(thr);
    }
  }
  return 0L;
}
 
Example 11
Source File: SymbolicLinkHelper.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the last modified time for a symbolic link.
 *
 * Note: symbolic links are not followed (NOFOLLOW_LINKS LinkOption)
 *
 * @param link the path to the symbolic link
 * @return last modified time of the symbolic link
 */
public static long getLastModifiedTime(String link) {
  if (nonNull(link)) {
    try {
      Path linkPath = Paths.get(link);
      if (nonNull(linkPath)) {
        FileTime fileTimeObject = Files.getLastModifiedTime(linkPath, LinkOption.NOFOLLOW_LINKS);
        if (nonNull(fileTimeObject)) {
          return fileTimeObject.toMillis();
        }
      }
    } catch (Throwable thr) {
      Log.error("Unexpected exception invoking method: %s", thr.getLocalizedMessage());
      Log.exception(thr);
    }
  }
  return 0L;
}
 
Example 12
Source File: ReflectUtil.java    From DevToolBox with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 从jar包中查找指定接口的一个实现类 非反射
 *
 * @param interfaceClass
 * @param jarPath
 * @return
 * @throws Exception
 */
public static Class findImplementFromJar(Class interfaceClass, URL jarPath) throws Exception {
    URL url = new URL("jar:" + jarPath.toString() + "!/");
    JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
    JarFile jarFile = jarConnection.getJarFile();
    Enumeration<JarEntry> je = jarFile.entries();
    boolean flag = false;
    while (je.hasMoreElements()) {
        JarEntry e = je.nextElement();
        String n = e.getName();
        FileTime ft = e.getLastModifiedTime();
        if (DateUtils.addDays(new Date(), -100).getTime() - ft.toMillis() > 0) {
            LOGGER.info("jar文件时间超过100天,跳过查找实现类:" + jarFile.getName().substring(jarFile.getName().lastIndexOf("\\")) + ft.toString());
            return null;
        } else {
            if (!flag) {
                flag = true;
                LOGGER.info("在" + jarFile.getName().substring(jarFile.getName().lastIndexOf("\\")) + "中查找实现类");
            }
        }
        if (n.endsWith(".class")) {
            n = n.substring(0, n.length() - 6);
            n = n.replace('/', '.');
            Class currentClass = ClassLoader.getSystemClassLoader().loadClass(n);
            if (interfaceClass.isAssignableFrom(currentClass) && !n.equals(interfaceClass.getName())) {
                return currentClass;
            }
        }
    }
    return null;
}
 
Example 13
Source File: FileTools.java    From MyBox with Apache License 2.0 5 votes vote down vote up
public static long getFileCreateTime(final String filename) {
    try {
        FileTime t = Files.readAttributes(Paths.get(filename), BasicFileAttributes.class).creationTime();
        return t.toMillis();
    } catch (Exception e) {
        return -1;
    }
}
 
Example 14
Source File: CollectionPathMatcher.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public boolean hasNext() {

      while (true) {
        if (!dirStreamIterator.hasNext()) {
          nextMFile = null;
          return false;
        }

        try {
          Path nextPath = dirStreamIterator.next();
          BasicFileAttributes attr = Files.readAttributes(nextPath, BasicFileAttributes.class);

          if (wantSubdirs && attr.isDirectory()) { // dont filter subdirectories
            subdirs.add(new OneDirIterator(nextPath, subdirs));
            continue;
          }

          if (!matcher.matches(nextPath)) // otherwise apply the filter specified by the specp
            continue;

          if (olderThanMillis > 0) {
            FileTime last = attr.lastModifiedTime();
            long millisSinceModified = now - last.toMillis();
            if (millisSinceModified < olderThanMillis)
              continue;
          }
          nextMFile = new MFileOS7(nextPath, attr);
          return true;

        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
 
Example 15
Source File: DcFixedWindowRollingPolicy.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * アーカイブされているログが最大保持世代数のときに最古の アーカイブログを削除する.
 * @param parent アーカイブログが格納されているディレクトリの親ディレクトリを示すオブジェクト
 */
private void removeOldestArchiveLog(File parent) {
    // アーカイブファイル数が保持世代(12世代)を超える場合は、最古のファイルを削除する
    File[] files = parent.listFiles();
    File oldest = null;
    FileTime oldestTime = null;
    if (files.length >= maxIndex - minIndex + 1) {
        for (File archive : files) {
            if (null == oldest) {
                oldest = archive;
            } else {
                try {
                    FileTime archiveTime = Files.getLastModifiedTime(archive.toPath());
                    oldestTime = Files.getLastModifiedTime(oldest.toPath());
                    if (archiveTime.toMillis() < oldestTime.toMillis()) {
                        oldest = archive;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (null != oldest && oldest.exists()) {
            logger.info("olddest archive file will be deleted.");
            logger.info("oldestFile Name: " + oldest.getPath() + ", timestamp: " + oldestTime.toMillis());
            logger.info("number of existing files:" + files.length + ", max number of files: "
                    + (maxIndex - minIndex + 1));
            if (oldest.delete()) {
                logger.warn("Failed to oldest archive file: " + oldest.getPath());
            }
        }
    }
}
 
Example 16
Source File: UrlTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void headers() throws IOException {
  byte[] bytes = {1, 2, 3};
  Files.write(path, bytes);
  FileTime lastModified = Files.getLastModifiedTime(path);

  URL url = path.toUri().toURL();
  URLConnection conn = url.openConnection();

  // read header fields directly
  assertThat(conn.getHeaderFields()).containsEntry("content-length", ImmutableList.of("3"));
  assertThat(conn.getHeaderFields())
      .containsEntry("content-type", ImmutableList.of("application/octet-stream"));

  if (lastModified != null) {
    assertThat(conn.getHeaderFields()).containsKey("last-modified");
    assertThat(conn.getHeaderFields()).hasSize(3);
  } else {
    assertThat(conn.getHeaderFields()).hasSize(2);
  }

  // use the specific methods for reading the expected headers
  assertThat(conn.getContentLengthLong()).isEqualTo(Files.size(path));
  assertThat(conn.getContentType()).isEqualTo("application/octet-stream");

  if (lastModified != null) {
    // The HTTP date format does not include milliseconds, which means that the last modified time
    // returned from the connection may not be exactly the same as that of the file system itself.
    // The difference should less than 1000ms though, and should never be greater.
    long difference = lastModified.toMillis() - conn.getLastModified();
    assertThat(difference).isIn(Range.closedOpen(0L, 1000L));
  } else {
    assertThat(conn.getLastModified()).isEqualTo(0L);
  }
}
 
Example 17
Source File: SchedulerBackupRunner.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private long getCreationTime(File file) {
    try {
        BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
        FileTime fileTime = attr.creationTime();
        return fileTime.toMillis();
    } catch (IOException e) {
        LOGGER.error("", e);
        // handle exception
        return 0l;
    }
}
 
Example 18
Source File: BOMResolver.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
private boolean canUseCache() throws IOException {
    if (CACHE_FILE.exists()) {
        BasicFileAttributes attr = Files.readAttributes(CACHE_FILE.toPath(), BasicFileAttributes.class);
        FileTime fileTime = attr != null ? attr.creationTime() : null;
        Long time = fileTime != null ? fileTime.toMillis() : null;
        // Update the cache every day
        return time != null && time.compareTo(System.currentTimeMillis() - 1000 * 60 * 60 * 24) > 0;
    }

    return false;
}
 
Example 19
Source File: DirectoryCollection.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public boolean hasNext() {
  while (true) {
    // if (debug && count % 100 == 0) System.out.printf("%d ", count);
    count++;
    if (!dirStreamIterator.hasNext()) {
      nextMFile = null;
      return false;
    }

    long now = System.currentTimeMillis();
    try {
      Path nextPath = dirStreamIterator.next();
      BasicFileAttributes attr = Files.readAttributes(nextPath, BasicFileAttributes.class);
      if (attr.isDirectory())
        continue;
      FileTime last = attr.lastModifiedTime();
      long millisSinceModified = now - last.toMillis();
      if (millisSinceModified < olderThanMillis)
        continue;
      nextMFile = new MFileOS7(nextPath, attr);
      return true;

    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example 20
Source File: DiagnosticsHelper.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static Long getFileCreationTime(File file) throws IOException {
    Path p = Paths.get(file.getAbsolutePath());
    BasicFileAttributes view = Files.getFileAttributeView(p, BasicFileAttributeView.class).readAttributes();
    FileTime fileTime = view.creationTime();
    return fileTime.toMillis();
}