java.nio.file.attribute.FileTime Java Examples

The following examples show how to use java.nio.file.attribute.FileTime. 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: CommandRebuildTest.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Expectation is that files '.n4js.projectstate' and 'src-gen/Module.js' are changed due to rebuild action. */
@Test
public void testCommandRebuild() throws Exception {
	test("class A { foo(a: A) { } } class Main { main(a: A) { a.foo(null); } }");

	// send command under test
	ExecuteCommandParams cmdCleanParams = new ExecuteCommandParams(N4JSCommandService.N4JS_REBUILD,
			Collections.emptyList());
	CompletableFuture<Object> future = languageServer.executeCommand(cmdCleanParams);
	future.join();

	// wait for previous command to finish
	joinServerRequests();

	// evaluate
	assertNoIssues();
	FileTime prjStateTime = Files.readAttributes(prjStatePath, BasicFileAttributes.class).lastModifiedTime();
	FileTime genFileTime = Files.readAttributes(genFileStatePath, BasicFileAttributes.class).lastModifiedTime();
	assertNotEquals(FILE_TIME_MILLISECONDS, prjStateTime.toMillis());
	assertNotEquals(FILE_TIME_MILLISECONDS, genFileTime.toMillis());
}
 
Example #2
Source File: WorkspaceGeneratorTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void workspaceIsNotRewrittenIfContentsHaveNotChanged() throws IOException {
  {
    generator.addFilePath(Paths.get("./Project.xcodeproj"));
    clock.setCurrentTimeMillis(49152);
    Path workspacePath = generator.writeWorkspace();
    assertThat(
        projectFilesystem.getLastModifiedTime(workspacePath.resolve("contents.xcworkspacedata")),
        equalTo(FileTime.fromMillis(49152L)));
  }

  {
    WorkspaceGenerator generator2 =
        new WorkspaceGenerator(projectFilesystem, "ws", Paths.get("."));
    generator2.addFilePath(Paths.get("./Project.xcodeproj"));
    clock.setCurrentTimeMillis(64738);
    Path workspacePath2 = generator2.writeWorkspace();
    assertThat(
        projectFilesystem.getLastModifiedTime(workspacePath2.resolve("contents.xcworkspacedata")),
        equalTo(FileTime.fromMillis(49152L)));
  }
}
 
Example #3
Source File: FileScanner.java    From jesterj with Apache License 2.0 6 votes vote down vote up
/**
 * A default, reusable and overridable means of adding file attributes to a document
 *
 * @param attributes The attributes of the scanned file as returned by
 *                   {@link java.nio.file.Files#getFileAttributeView(Path, Class, LinkOption...)}
 * @param doc        The document representing the scanned file to which attributes should be added.
 */
default void addAttrs(BasicFileAttributes attributes, DocumentImpl doc) {
  if (attributes != null) {
    FileTime modifiedTime = attributes.lastModifiedTime();
    FileTime accessTime = attributes.lastAccessTime();
    FileTime creationTime = attributes.creationTime();
    if (modifiedTime != null) {
      doc.put("modified", String.valueOf(modifiedTime.toMillis()));
    }
    if (accessTime != null) {
      doc.put("accessed", String.valueOf(accessTime.toMillis()));
    }
    if (creationTime != null) {
      doc.put("created", String.valueOf(creationTime.toMillis()));
    }
    doc.put("file_size", String.valueOf(attributes.size()));
  }
}
 
Example #4
Source File: TestExtraTime.java    From dragonwell8_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 #5
Source File: ZipTest.java    From turbine with Apache License 2.0 6 votes vote down vote up
@Test
public void attributes() throws Exception {
  Path path = temporaryFolder.newFile("test.jar").toPath();
  Files.delete(path);
  try (FileSystem fs =
      FileSystems.newFileSystem(
          URI.create("jar:" + path.toUri()), ImmutableMap.of("create", "true"))) {
    for (int i = 0; i < 3; i++) {
      String name = "entry" + i;
      byte[] bytes = name.getBytes(UTF_8);
      Path entry = fs.getPath(name);
      Files.write(entry, bytes);
      Files.setLastModifiedTime(entry, FileTime.fromMillis(0));
    }
  }
  assertThat(actual(path)).isEqualTo(expected(path));
}
 
Example #6
Source File: FileUtils.java    From helidon-build-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Ensure that the given file exists, and update the modified time if it does.
 *
 * @param file The file.
 * @return The file.
 */
public static Path touch(Path file) {
    if (Files.exists(file)) {
        final long currentTime = System.currentTimeMillis();
        final long lastModified = lastModifiedSeconds(file);
        final long lastModifiedPlusOneSecond = lastModified + 1000;
        final long newTime = Math.max(currentTime, lastModifiedPlusOneSecond);
        try {
            Files.setLastModifiedTime(file, FileTime.fromMillis(newTime));
            return file;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    } else {
        return ensureFile(file);
    }
}
 
Example #7
Source File: FakeFileAttributes.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * @param fileKey something uniquely representing the file this is for
 * @param isFileElseDir this is for a file, iff this is true. Otherwise it's a dir. Never a
 *     symlink or "other" type.
 * @param size file size. Probably only makes sense for files.
 */
protected FakeFileAttributes(Object fileKey, boolean isFileElseDir, long size) {
  this.fileKeyObj = fileKey;
  this.isFileElseDir = isFileElseDir;
  this.fileSize = size;
  this.timestamp = FileTime.fromMillis(System.currentTimeMillis());
}
 
Example #8
Source File: Basic.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static void ts(Instant instant, String expected) {
    String result = FileTime.from(instant).toString();
    if (!result.equals(expected)) {
        System.err.format("FileTime.from(%s).toString() failed\n", instant);
        System.err.format("Expected: %s\n", expected);
        System.err.format("     Got: %s\n", result);
        throw new RuntimeException();
    }
}
 
Example #9
Source File: BasicFileAttributeViewTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void getLastAccessTimeAttributeOfFile_shouldReturnEpoch() throws IOException {
  writeToCache("/file.txt");
  commitToMaster();
  initGitFileSystem();

  GfsFileAttributeView.Basic view = provider.getFileAttributeView(gfs.getPath("/file.txt"), GfsFileAttributeView.Basic.class);
  assertNotNull(view);
  assertEquals(FileTime.fromMillis(0), readAttribute(view, GfsFileAttributeView.Basic.LAST_ACCESS_TIME_NAME));
}
 
Example #10
Source File: DefaultProjectFilesystem.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Sets the last modified time for the given path. */
@Override
public Path setLastModifiedTime(Path pathRelativeToProjectRoot, FileTime time)
    throws IOException {
  Path path = getPathForRelativePath(pathRelativeToProjectRoot);
  return Files.setLastModifiedTime(path, time);
}
 
Example #11
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 #12
Source File: S3Utils.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
@Override
public FileVisitResult postVisitDirectory(java.nio.file.Path dir, IOException exc) throws IOException
{
  if (indexAttributes != null && dataAttributes != null) {
    partitionSize = indexAttributes.size() + dataAttributes.size();
    callback.foundImage(dir, partitionSize, lastAccessTime);
    indexAttributes = null;
    dataAttributes = null;
    lastAccessTime = FileTime.from(Instant.now());
    partitionSize = 0L;
  }
  return FileVisitResult.CONTINUE;
}
 
Example #13
Source File: Basic.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static void ts(long v, TimeUnit unit, String expected) {
    String result = FileTime.from(v, unit).toString();
    if (!result.equals(expected)) {
        System.err.format("FileTime.from(%d, %s).toString() failed\n", v, unit);
        System.err.format("Expected: %s\n", expected);
        System.err.format("     Got: %s\n", result);
        throw new RuntimeException();
    }
}
 
Example #14
Source File: FileDirectoryTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void requireThatExistingDirWithInvalidContentIsDeleted() throws IOException {
    FileDirectory fileDirectory = new FileDirectory(temporaryFolder.getRoot());

    String subdirName = "subdir";
    File subDirectory = new File(temporaryFolder.getRoot(), subdirName);
    createFileInSubDir(subDirectory, "foo", "some content");
    FileReference fileReference = fileDirectory.addFile(subDirectory);
    File dir = fileDirectory.getFile(fileReference);
    assertTrue(dir.exists());
    File foo = new File(dir, "foo");
    assertTrue(foo.exists());
    FileTime fooCreatedTimestamp = Files.readAttributes(foo.toPath(), BasicFileAttributes.class).creationTime();
    assertFalse(new File(dir, "doesnotexist").exists());
    assertEquals("bebc5a1aee74223d", fileReference.value());

    // Remove a file, directory should be deleted before adding a new file
    try { Thread.sleep(1000);} catch (InterruptedException e) {/*ignore */} // Needed since we have timestamp resolution of 1 second
    Files.delete(Paths.get(fileDirectory.getPath(fileReference)).resolve("subdir").resolve("foo"));
    fileReference = fileDirectory.addFile(subDirectory);
    dir = fileDirectory.getFile(fileReference);
    File foo2 = new File(dir, "foo");
    assertTrue(dir.exists());
    assertTrue(foo2.exists());
    FileTime foo2CreatedTimestamp = Files.readAttributes(foo2.toPath(), BasicFileAttributes.class).creationTime();
    // Check that creation timestamp is newer than the old one to be sure that a new file was written
    assertTrue(foo2CreatedTimestamp.compareTo(fooCreatedTimestamp) > 0);
    assertFalse(new File(dir, "doesnotexist").exists());
    assertEquals("bebc5a1aee74223d", fileReference.value());
}
 
Example #15
Source File: MCRStoredNode.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Renames this node.
 * 
 * @param name
 *            the new file name
 */
public void renameTo(String name) throws IOException {
    Path oldPath = path;
    Path newPath = path.resolveSibling(name);
    Files.move(oldPath, newPath);
    Files.setLastModifiedTime(newPath, FileTime.from(Instant.now()));
    path = newPath;
    writeData(e -> e.setAttribute(NAME_ATT, name));
    getRoot().saveAdditionalData();
}
 
Example #16
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 #17
Source File: TestExtraTime.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static void check(FileTime mtime, FileTime atime, FileTime ctime,
                  ZipEntry ze, byte[] extra) {
    /*
    System.out.printf("    mtime [%tc]: [%tc]/[%tc]%n",
                      mtime.to(TimeUnit.MILLISECONDS),
                      ze.getTime(),
                      ze.getLastModifiedTime().to(TimeUnit.MILLISECONDS));
     */
    if (mtime.to(TimeUnit.SECONDS) !=
        ze.getLastModifiedTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing mtime failed!");
    if (atime != null &&
        atime.to(TimeUnit.SECONDS) !=
        ze.getLastAccessTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing atime failed!");
    if (ctime != null &&
        ctime.to(TimeUnit.SECONDS) !=
        ze.getCreationTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing ctime failed!");
    if (extra != null) {
        // if extra data exists, the current implementation put it at
        // the end of the extra data array (implementation detail)
        byte[] extra1 = ze.getExtra();
        if (extra1 == null || extra1.length < extra.length ||
            !Arrays.equals(Arrays.copyOfRange(extra1,
                                              extra1.length - extra.length,
                                              extra1.length),
                           extra)) {
            throw new RuntimeException("Timestamp: storing extra field failed!");
        }
    }
}
 
Example #18
Source File: TestExtraTime.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Throwable{

        File src = new File(System.getProperty("test.src", "."), "TestExtraTime.java");
        if (src.exists()) {
            long time = src.lastModified();
            FileTime mtime = FileTime.from(time, TimeUnit.MILLISECONDS);
            FileTime atime = FileTime.from(time + 300000, TimeUnit.MILLISECONDS);
            FileTime ctime = FileTime.from(time - 300000, TimeUnit.MILLISECONDS);
            TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");

            for (byte[] extra : new byte[][] { null, new byte[] {1, 2, 3}}) {
                test(mtime, null, null, null, extra);
                // ms-dos 1980 epoch problem
                test(FileTime.from(10, TimeUnit.MILLISECONDS), null, null, null, extra);
                // non-default tz
                test(mtime, null, null, tz, extra);

                test(mtime, atime, null, null, extra);
                test(mtime, null, ctime, null, extra);
                test(mtime, atime, ctime, null, extra);

                test(mtime, atime, null, tz, extra);
                test(mtime, null, ctime, tz, extra);
                test(mtime, atime, ctime, tz, extra);
            }
        }

        testNullHandling();
        testTimeConversions();
    }
 
Example #19
Source File: Basic.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static void eq(long v1, TimeUnit u1, long v2, TimeUnit u2) {
    FileTime t1 = FileTime.from(v1, u1);
    FileTime t2 = FileTime.from(v2, u2);
    if (!t1.equals(t2))
        throw new RuntimeException("not equal");
    if (t1.hashCode() != t2.hashCode())
        throw new RuntimeException("hashCodes should be equal");
}
 
Example #20
Source File: WellKnowns.java    From libreveris with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static FileTime getJarTime ()
{
    long millis = JAR_FILE.getEntry("META-INF/MANIFEST.MF")
            .getTime();

    return FileTime.fromMillis(millis);
}
 
Example #21
Source File: BuildConfigurationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteBuildConfiguration() throws IOException, InterruptedException {
  ImmutableSortedMap<String, String> config =
      ImmutableSortedMap.<String, String>naturalOrder().put("SOME_FLAG", "value").build();
  Path filePath = Paths.get("new-dir/test.xcconfig");

  BuildConfiguration.writeBuildConfiguration(projectFilesystem, filePath, config, false);
  Optional<String> fileContents = projectFilesystem.readFileIfItExists(filePath);
  assertEquals("SOME_FLAG = value\n", fileContents.get());

  // Verify that the same file is not rewritten.
  FileTime modifiedTime = projectFilesystem.getLastModifiedTime(filePath);
  BuildConfiguration.writeBuildConfiguration(projectFilesystem, filePath, config, false);
  FileTime newModifiedTime = projectFilesystem.getLastModifiedTime(filePath);
  assertEquals(modifiedTime, newModifiedTime);

  Thread.sleep(100);

  // Verify that a new file is
  config =
      ImmutableSortedMap.<String, String>naturalOrder()
          .put("SOME_FLAG", "value new y'all")
          .build();
  BuildConfiguration.writeBuildConfiguration(projectFilesystem, filePath, config, false);
  newModifiedTime = projectFilesystem.getLastModifiedTime(filePath);
  assertNotEquals(modifiedTime, newModifiedTime);
}
 
Example #22
Source File: FakeProjectFilesystemTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void fileModifiedTimeIsSetOnInitialWrite() throws IOException {
  SettableFakeClock clock = new SettableFakeClock(49152, 0);
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem(clock);
  filesystem.touch(Paths.get("foo"));
  assertEquals(filesystem.getLastModifiedTime(Paths.get("foo")), FileTime.fromMillis(49152));
}
 
Example #23
Source File: ResourceManager.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
@Override
@FromAnyThread
public synchronized void assetRequested(@NotNull final AssetKey key) {

    if (key.getCacheType() == null) {
        return;
    }

    final String extension = key.getExtension();
    if (StringUtils.isEmpty(extension)){
        return;
    }

    final ObjectDictionary<String, Reference> table = getAssetCacheTable();
    final Reference reference = table.get(key.getName());
    if (reference == null) {
        return;
    }

    final Path realFile = getRealFile(Paths.get(key.getName()));
    if (realFile == null || !Files.exists(realFile)) {
        return;
    }

    try {

        final long timestamp = reference.getLong();

        final FileTime lastModifiedTime = Files.getLastModifiedTime(realFile);
        if (lastModifiedTime.to(TimeUnit.MILLISECONDS) <= timestamp) {
            return;
        }

        final AssetManager assetManager = EditorUtil.getAssetManager();
        assetManager.deleteFromCache(key);

    } catch (final IOException e) {
        LOGGER.warning(e);
    }
}
 
Example #24
Source File: LoggingUpdaterUtil.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public static FileTime readModifiedTime() throws LoggingUpdaterException {

        String carbonConfigDirPath = CarbonUtils.getCarbonConfigDirPath();
        File log4j2File = new File(carbonConfigDirPath + File.separator + "log4j2.properties");
        try {
            BasicFileAttributes log4j2FileAttributes
                    = Files.getFileAttributeView(log4j2File.toPath(), BasicFileAttributeView.class).readAttributes();
            return log4j2FileAttributes.lastModifiedTime();
        } catch (IOException e) {
            throw new LoggingUpdaterException("Error while reading log4j2.properties", e);
        }
    }
 
Example #25
Source File: Basic.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void ts(Instant instant, String expected) {
    String result = FileTime.from(instant).toString();
    if (!result.equals(expected)) {
        System.err.format("FileTime.from(%s).toString() failed\n", instant);
        System.err.format("Expected: %s\n", expected);
        System.err.format("     Got: %s\n", result);
        throw new RuntimeException();
    }
}
 
Example #26
Source File: GeoIpService.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Download (if absent or old) the GeoIpLite data file and then try to load it.
 *
 * @return True if the data is available, false otherwise.
 */
private synchronized boolean isDataAvailable() {
    if (downloading) {
        // we are currently downloading the database
        return false;
    }

    if (databaseReader != null) {
        // everything is initialized
        return true;
    }

    if (Files.exists(dataFile)) {
        try {
            FileTime lastModifiedTime = Files.getLastModifiedTime(dataFile);
            if (Duration.between(lastModifiedTime.toInstant(), Instant.now()).toDays() <= UPDATE_INTERVAL_DAYS) {
                startReading();

                // don't fire the update task - we are up to date
                return true;
            } else {
                logger.debug("GEO IP database is older than " + UPDATE_INTERVAL_DAYS + " Days");
            }
        } catch (IOException ioEx) {
            logger.logException("Failed to load GeoLiteAPI database", ioEx);
            return false;
        }
    }

    //set the downloading flag in order to fix race conditions outside
    downloading = true;

    // File is outdated or doesn't exist - let's try to download the data file!
    // use bukkit's cached threads
    bukkitService.runTaskAsynchronously(this::updateDatabase);
    return false;
}
 
Example #27
Source File: FakeProjectFilesystem.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public Path setLastModifiedTime(Path path, FileTime time) throws IOException {
  Path normalizedPath = MorePaths.normalize(path);
  if (!exists(normalizedPath)) {
    throw new NoSuchFileException(path.toString());
  }
  fileLastModifiedTimes.put(normalizedPath, time);
  return normalizedPath;
}
 
Example #28
Source File: SetLastModifiedTime.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Exercise Files.setLastModifiedTime on the given file
 */
void test(Path path) throws Exception {
    FileTime now = Files.getLastModifiedTime(path);
    FileTime zero = FileTime.fromMillis(0L);

    Path result = Files.setLastModifiedTime(path, zero);
    assertTrue(result == path);
    assertEquals(Files.getLastModifiedTime(path), zero);

    result = Files.setLastModifiedTime(path, now);
    assertTrue(result == path);
    assertEquals(Files.getLastModifiedTime(path), now);
}
 
Example #29
Source File: TestExtraTime.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static void check(FileTime mtime, FileTime atime, FileTime ctime,
                  ZipEntry ze, byte[] extra) {
    /*
    System.out.printf("    mtime [%tc]: [%tc]/[%tc]%n",
                      mtime.to(TimeUnit.MILLISECONDS),
                      ze.getTime(),
                      ze.getLastModifiedTime().to(TimeUnit.MILLISECONDS));
     */
    if (mtime.to(TimeUnit.SECONDS) !=
        ze.getLastModifiedTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing mtime failed!");
    if (atime != null &&
        atime.to(TimeUnit.SECONDS) !=
        ze.getLastAccessTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing atime failed!");
    if (ctime != null &&
        ctime.to(TimeUnit.SECONDS) !=
        ze.getCreationTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing ctime failed!");
    if (extra != null) {
        // if extra data exists, the current implementation put it at
        // the end of the extra data array (implementation detail)
        byte[] extra1 = ze.getExtra();
        if (extra1 == null || extra1.length < extra.length ||
            !Arrays.equals(Arrays.copyOfRange(extra1,
                                              extra1.length - extra.length,
                                              extra1.length),
                           extra)) {
            throw new RuntimeException("Timestamp: storing extra field failed!");
        }
    }
}
 
Example #30
Source File: CreationDateResolver.java    From tutorials with MIT License 5 votes vote down vote up
public Instant resolveCreationTimeWithBasicAttributes(Path path) {
    try {
        final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
        final FileTime fileTime = attr.creationTime();

        return fileTime.toInstant();
    } catch (IOException ex) {
        throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
    }
}