Example usage for java.nio.file Files getLastModifiedTime

List of usage examples for java.nio.file Files getLastModifiedTime

Introduction

In this page you can find the example usage for java.nio.file Files getLastModifiedTime.

Prototype

public static FileTime getLastModifiedTime(Path path, LinkOption... options) throws IOException 

Source Link

Document

Returns a file's last modified time.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path path = FileSystems.getDefault().getPath("/home/docs/users.txt");
    System.out.println(Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS));
}

From source file:Test.java

private static void displayFileAttributes(Path path) throws Exception {
    String format = "Exists: %s %n" + "notExists: %s %n" + "Directory: %s %n" + "Regular: %s %n"
            + "Executable: %s %n" + "Readable: %s %n" + "Writable: %s %n" + "Hidden: %s %n" + "Symbolic: %s %n"
            + "Last Modified Date: %s %n" + "Size: %s %n";

    System.out.printf(format, Files.exists(path, LinkOption.NOFOLLOW_LINKS),
            Files.notExists(path, LinkOption.NOFOLLOW_LINKS),
            Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS),
            Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS), Files.isExecutable(path),
            Files.isReadable(path), Files.isWritable(path), Files.isHidden(path), Files.isSymbolicLink(path),
            Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS), Files.size(path));
}

From source file:com.ignorelist.kassandra.steam.scraper.FileCache.java

private long getModified(String key) throws IOException {
    FileTime lastModifiedTime = Files.getLastModifiedTime(buildCacheFile(key), LinkOption.NOFOLLOW_LINKS);
    return lastModifiedTime.toMillis();
}

From source file:org.sakuli.datamodel.helper.TestSuiteHelperTest.java

@Test
public void testModifyFiles() throws Exception {
    Path path = Paths.get("temp-testsuite.suite");
    try {//w w w .jav a 2s  .  c  om
        String source = "line1\r\n\r\nbla\r\n";
        FileUtils.writeStringToFile(path.toFile(), source);
        FileTime beforeTimeStamp = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
        Thread.sleep(1100);

        String result = TestSuiteHelper.prepareTestSuiteFile(path);
        assertEquals(result, "line1\r\n//\r\nbla\r\n");
        FileTime afterTimeStamp = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
        assertNotEquals(beforeTimeStamp, afterTimeStamp);
    } finally {
        Files.deleteIfExists(path);
    }
}

From source file:org.sakuli.datamodel.helper.TestSuiteHelperTest.java

@Test
public void testNotModifyFiles() throws Exception {
    Path path = Paths.get("temp-testsuite.suite");
    try {//from  www .jav a2  s.com
        String source = "line1\r\nbla\r\n";
        FileUtils.writeStringToFile(path.toFile(), source);
        FileTime beforeTimeStamp = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
        Thread.sleep(1100);

        String result = TestSuiteHelper.prepareTestSuiteFile(path);
        assertEquals(source, result);
        FileTime afterTimeStamp = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
        assertEquals(beforeTimeStamp, afterTimeStamp);
    } finally {
        Files.deleteIfExists(path);
    }
}

From source file:org.alfresco.repo.bulkimport.impl.DirectoryAnalyserImpl.java

/**
 * @see org.alfresco.repo.bulkimport.DirectoryAnalyser#analyseDirectory(org.alfresco.repo.bulkimport.ImportableItem, java.nio.file.DirectoryStream.Filter)
 *///from   w ww . jav  a 2 s .c  o  m
public AnalysedDirectory analyseDirectory(ImportableItem directory, DirectoryStream.Filter<Path> filter) {
    Path directoryFile = directory.getHeadRevision().getContentFile();
    AnalysedDirectory result = new AnalysedDirectory(listFiles(directoryFile, filter));

    if (log.isDebugEnabled()) {
        log.debug("Analysing directory " + FileUtils.getFileName(directoryFile) + "...");
    }

    // Build up the list of ImportableItems from the directory listing
    for (Path file : result.getOriginalPaths()) {
        // MNT-9763 bulkimport fails when there is a very large LastModified timestamp.
        String isoDate = null;
        try {
            isoDate = ISO8601DateFormat
                    .format(new Date(Files.getLastModifiedTime(file, LinkOption.NOFOLLOW_LINKS).toMillis()));
            ISO8601DateFormat.parse(isoDate);
        } catch (PlatformRuntimeException | IOException e) {
            log.warn("Failed to convert date " + isoDate + " to string for " + file.getFileName(), e);
            importStatus.incrementNumberOfUnreadableEntries();
            continue;
        }

        if (log.isTraceEnabled()) {
            log.trace("Scanning file " + FileUtils.getFileName(file) + "...");
        }

        if (Files.isReadable(file)) {
            try {
                nameChecker.evaluate(file.getFileName().toString());
            } catch (ConstraintException e) {
                if (log.isWarnEnabled()) {
                    log.warn("Skipping file with invalid name: '" + FileUtils.getFileName(file) + "'.");
                }
                // mark file with invalid name as unreadable
                importStatus.incrementNumberOfUnreadableEntries();

                continue;
            }

            if (isVersionFile(file)) {
                addVersionFile(directory, result, file);
                importStatus.incrementNumberOfFilesScanned();
            } else if (isMetadataFile(file)) {
                addMetadataFile(directory, result, file);
                importStatus.incrementNumberOfFilesScanned();
            } else {
                boolean isDirectory = addParentFile(directory, result, file);

                if (isDirectory) {
                    importStatus.incrementNumberOfFoldersScanned();
                } else {
                    importStatus.incrementNumberOfFilesScanned();
                }
            }
        } else {
            if (log.isWarnEnabled()) {
                log.warn("Skipping unreadable file '" + FileUtils.getFileName(file) + "'.");
            }

            importStatus.incrementNumberOfUnreadableEntries();
        }
    }

    // Finally, remove any items from the list that aren't valid (don't have either a
    // contentFile or a metadataFile)
    Iterator<ImportableItem> iter = result.getImportableItems().iterator();

    while (iter.hasNext()) {
        ImportableItem importableItem = iter.next();

        if (!importableItem.isValid() || !isMetadataValid(importableItem)) {
            iter.remove();
        }
    }

    iter = result.getImportableDirectories().iterator();
    while (iter.hasNext()) {
        ImportableItem importableItem = iter.next();

        if (!importableItem.isValid()) {
            iter.remove();
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Finished analysing directory " + FileUtils.getFileName(directoryFile) + ".");
    }

    return result;
}

From source file:com.liferay.sync.engine.lan.server.file.LanFileServerHandler.java

protected void sendFile(final ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest,
        SyncFile syncFile) throws Exception {

    Path path = Paths.get(syncFile.getFilePathName());

    if (Files.notExists(path)) {
        _syncTrafficShapingHandler.decrementConnectionsCount();

        if (_logger.isTraceEnabled()) {
            Channel channel = channelHandlerContext.channel();

            _logger.trace("Client {}: file not found {}", channel.remoteAddress(), path);
        }//from  w  w  w  . j a va2  s  . c  o  m

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    if (_logger.isDebugEnabled()) {
        Channel channel = channelHandlerContext.channel();

        _logger.debug("Client {}: sending file {}", channel.remoteAddress(), path);
    }

    long modifiedTime = syncFile.getModifiedTime();
    long previousModifiedTime = syncFile.getPreviousModifiedTime();

    if (OSDetector.isApple()) {
        modifiedTime = modifiedTime / 1000 * 1000;
        previousModifiedTime = previousModifiedTime / 1000 * 1000;
    }

    FileTime currentFileTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);

    long currentTime = currentFileTime.toMillis();

    if ((currentTime != modifiedTime) && (currentTime != previousModifiedTime)) {

        _syncTrafficShapingHandler.decrementConnectionsCount();

        Channel channel = channelHandlerContext.channel();

        _logger.error(
                "Client {}: file modified {}, currentTime {}, modifiedTime " + "{}, previousModifiedTime {}",
                channel.remoteAddress(), path, currentTime, modifiedTime, previousModifiedTime);

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK);

    long size = Files.size(path);

    HttpUtil.setContentLength(httpResponse, size);

    HttpHeaders httpHeaders = httpResponse.headers();

    MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();

    httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(syncFile.getName()));

    if (HttpUtil.isKeepAlive(fullHttpRequest)) {
        httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    channelHandlerContext.write(httpResponse);

    SyncChunkedFile syncChunkedFile = new SyncChunkedFile(path, size, 4 * 1024 * 1024, currentTime);

    ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(new HttpChunkedInput(syncChunkedFile),
            channelHandlerContext.newProgressivePromise());

    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            _syncTrafficShapingHandler.decrementConnectionsCount();

            if (channelFuture.isSuccess()) {
                return;
            }

            Throwable exception = channelFuture.cause();

            Channel channel = channelHandlerContext.channel();

            _logger.error("Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception);

            channelHandlerContext.close();
        }

    });

    if (!HttpUtil.isKeepAlive(fullHttpRequest)) {
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:onl.area51.filesystem.ftp.client.FTPClient.java

/**
 * Simple test to see if a remote file should be retrieved.
 * <p>//from  w  w w .  j  av  a  2  s  .  co m
 * This returns true if file does not exist, if the lengths don't match or the remote file's date is newer than the local file
 * <p>
 * @param file
 * @param ftp
 *             <p>
 * @return
 */
default boolean isPathRetrievable(Path file, FTPFile ftp) throws IOException {
    return !Files.exists(file, LinkOption.NOFOLLOW_LINKS) || Files.size(file) != ftp.getSize()
            || Files.getLastModifiedTime(file, LinkOption.NOFOLLOW_LINKS).toMillis() < ftp.getTimestamp()
                    .getTimeInMillis();
}