Example usage for java.io File setLastModified

List of usage examples for java.io File setLastModified

Introduction

In this page you can find the example usage for java.io File setLastModified.

Prototype

public boolean setLastModified(long time) 

Source Link

Document

Sets the last-modified time of the file or directory named by this abstract pathname.

Usage

From source file:maspack.fileutil.SafeFileUtils.java

/**
 * Internal copy file method.//from   w  w  w . j av  a  2s  . com
 * 
 * @param srcFile
 * the validated source file, must not be {@code null}
 * @param destFile
 * the validated destination file, must not be {@code null}
 * @param options
 * determine whether to use a file lock, and preserve date information
 * @throws IOException
 * if an error occurs
 */
private static void doCopyFile(File srcFile, File destFile, int options) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    File lockFile = new File(destFile.getAbsolutePath() + LOCK_EXTENSION);

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;

        // Create lock before starting transfer
        // NOTE: we are purposely not using the Java NIO FileLock, because that
        // is automatically removed when the JVM exits. We want this file to
        // persist to inform the system the transfer was never completed.
        if ((options & LOCK_FILE) != 0) {
            if (lockFile.exists()) {

                // if we are not cleaning old locks, throw error
                if ((options & CLEAN_LOCK) == 0) {
                    throw new IOException(
                            "Lock file exists, preventing a write to " + destFile.getAbsolutePath()
                                    + ".  Delete " + lockFile.getName() + " or set the CLEAN_LOCK option flag");
                }
            } else {
                lockFile.createNewFile(); // will always return true or throw
                                          // error
            }

        }

        while (pos < size) {
            count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
            pos += output.transferFrom(input, pos, count);
        }
    } finally {
        closeQuietly(output);
        closeQuietly(fos);
        closeQuietly(input);
        closeQuietly(fis);
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }

    if ((options & PRESERVE_DATE) != 0) {
        destFile.setLastModified(srcFile.lastModified());
    }

    // successful copy, delete lock file
    deleteQuietly(lockFile);

}

From source file:com.dotosoft.dotoquiz.tools.thirdparty.PicasawebClient.java

public void setUpdatedDate(GphotoEntry album, final PhotoEntry photoToChange, File localFile) {
    try {/* w  w w . j  ava2  s .  c o m*/
        final boolean SETUPDATE_WORKS = false;

        if (SETUPDATE_WORKS) {
            List<GphotoEntry> photos = getPhotos(album);

            for (GphotoEntry photo : photos) {
                if (photo.getGphotoId().equals(photoToChange.getGphotoId())) {
                    DateTime time = new DateTime(localFile.lastModified());
                    time.setTzShift(0);

                    log.info("Setting Updated from " + photo.getUpdated() + " to " + time);
                    photo.setUpdated(time);
                    photo.update();
                    break;
                }
            }
        } else {
            // Since it doesn't work, the only option to avoid unnecessary uploads/downloads
            // is to set the lastModified file time on the local file.
            log.info(
                    "Setting local file time to " + photoToChange.getUpdated() + " for " + localFile.getName());
            localFile.setLastModified(photoToChange.getUpdated().getValue());
        }
    } catch (Exception ex) {
        log.error("Unable to change lastUpdate date for " + photoToChange.getTitle().getPlainText());
    }
}

From source file:RestoreService.java

/**
 * execute restore process/*from  www.j  av a2 s.c o  m*/
 *
 * @throws Exception
 */
public void run() throws Exception {
    // load index
    Collection<File> bckIdxCollection = FileUtils.listFiles(repository.getMetaPath(),
            new WildcardFileFilter(bckIdxName + "*"), TrueFileFilter.INSTANCE);

    // TODO Lebeda - check only one index file

    // find files ro restore
    Set<VOBackupFile> oldFileSet = repository.collectBackupedFilesFromIndex(bckIdxCollection);
    Set<VOBackupFile> restoreFileSet = new HashSet<>();
    for (final String path : pathToRestoreList) {
        //noinspection unchecked
        restoreFileSet.addAll((Collection<VOBackupFile>) CollectionUtils.select(oldFileSet, new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                VOBackupFile voBackupFile = (VOBackupFile) object;
                return StringUtils.startsWithIgnoreCase(voBackupFile.getPath(), path + File.separator);
            }
        }));
    }

    // create directory if not exists
    for (String pathForRestore : pathToRestoreList) {
        pathForRestore = changedPathToRestore(pathForRestore, targetPath);
        File baseFile = new File(pathForRestore);
        if (!baseFile.exists()) {
            //noinspection ResultOfMethodCallIgnored
            baseFile.mkdirs(); // TODO Lebeda - oetit hodnotu
        }
    }

    // find files in directory
    List<VOBackupFile> newFileList = new ArrayList<>();
    for (String pathForRestore : pathToRestoreList) {
        pathForRestore = changedPathToRestore(pathForRestore, targetPath);
        //noinspection unchecked
        final Collection<File> fileColection = FileUtils.listFiles(new File(pathForRestore),
                TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);

        for (File file : fileColection) {
            newFileList.add(new VOBackupFile(file));
        }
    }

    // delete files not in index (new or changed)
    //noinspection unchecked
    final Collection<VOBackupFile> toDelete = (Collection<VOBackupFile>) CollectionUtils.subtract(newFileList,
            restoreFileSet);
    for (VOBackupFile voBackupFile : toDelete) {
        FileUtils.forceDelete(new File(voBackupFile.getPath()));
        logger.debug("deleted file: {}", voBackupFile.getPath());
    }

    // restore files not in direcroty
    //noinspection unchecked
    final Collection<VOBackupFile> toRestore = (Collection<VOBackupFile>) CollectionUtils
            .subtract(restoreFileSet, newFileList);

    final Collection<VOBackupFile> toTime = new ArrayList<>();
    for (VOBackupFile voBackupFile : toRestore) {
        String path = changedPathToRestore(voBackupFile.getPath(), targetPath);
        if (!voBackupFile.isSymLink()) {
            if (voBackupFile.isDirectory()) {
                File dir = new File(path);
                dir.mkdirs(); // TODO Lebeda - zajistit oeten
                toTime.add(voBackupFile);
                setAdvancedAttributes(voBackupFile, dir);
            } else if (voBackupFile.getSize() == 0) {
                File file = new File(path);
                file.createNewFile(); // TODO Lebeda - oetit
                file.setLastModified(voBackupFile.getModify().getTime());
                setAdvancedAttributes(voBackupFile, file);
            } else if (StringUtils.isNotBlank(voBackupFile.getFileHash())) {
                repository.restoreFile(voBackupFile, path);
            } else {
                // TODO Lebeda - chyba
                //                LoggerTools.log("unable to restore ${it}")
            }
        }
    }

    // symlinks restore at end
    for (VOBackupFile voBackupFile : toRestore) {
        String path = changedPathToRestore(voBackupFile.getPath(), targetPath);
        if (voBackupFile.isSymLink()) {
            Files.createSymbolicLink(Paths.get(path), Paths.get(voBackupFile.getSymlinkTarget()));
        }
    }

    for (VOBackupFile voBackupFile : toTime) {
        String path = changedPathToRestore(voBackupFile.getPath(), targetPath);
        File dir = new File(path);
        dir.setLastModified(voBackupFile.getModify().getTime());
    }

}

From source file:org.apache.spark.streaming.JavaAPISuite.java

private List<List<String>> fileTestPrepare(File testDir) throws IOException {
    File existingFile = new File(testDir, "0");
    Files.write("0\n", existingFile, Charset.forName("UTF-8"));
    assertTrue(existingFile.setLastModified(1000) && existingFile.lastModified() == 1000);

    List<List<String>> expected = Arrays.asList(Arrays.asList("0"));

    return expected;
}

From source file:com.virtualparadigm.packman.processor.JPackageManagerOld.java

public static boolean configureOld(File tempDir, Configuration configuration) {
    logger.info("PackageManager::configure()");
    boolean status = true;
    if (tempDir != null && configuration != null && !configuration.isEmpty()) {
        VelocityEngine velocityEngine = new VelocityEngine();
        Properties vProps = new Properties();
        vProps.setProperty("resource.loader", "string");
        vProps.setProperty("string.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.StringResourceLoader");
        velocityEngine.init(vProps);/*from  w  w w  .  j  av  a  2 s  . c om*/
        Template template = null;
        VelocityContext velocityContext = JPackageManagerOld.createVelocityContext(configuration);
        StringResourceRepository stringResourceRepository = StringResourceLoader.getRepository();
        String templateContent = null;
        StringWriter stringWriter = null;
        long lastModified;

        Collection<File> patchFiles = FileUtils.listFiles(
                new File(tempDir.getAbsolutePath() + "/" + JPackageManagerOld.PATCH_DIR_NAME + "/"
                        + JPackageManagerOld.PATCH_FILES_DIR_NAME),
                TEMPLATE_SUFFIX_FILE_FILTER, DirectoryFileFilter.DIRECTORY);

        if (patchFiles != null) {
            for (File pfile : patchFiles) {
                logger.debug("  processing patch fileset file: " + pfile.getAbsolutePath());
                try {
                    lastModified = pfile.lastModified();
                    templateContent = FileUtils.readFileToString(pfile);

                    if (templateContent.matches("(\\$)(\\{)([^\\}]*)(\\:)([^\\{]*)(\\})")) {
                        System.out.println("    converting $ to #");
                    }

                    templateContent = templateContent.replaceAll("#", "\\#");
                    templateContent = templateContent.replaceAll("(\\$)(\\{)([^\\}]*)(\\:)([^\\{]*)(\\})",
                            "#$2$3$4$5$6");

                    stringResourceRepository.putStringResource(JPackageManagerOld.CURRENT_TEMPLATE_NAME,
                            templateContent);
                    stringWriter = new StringWriter();
                    template = velocityEngine.getTemplate(JPackageManagerOld.CURRENT_TEMPLATE_NAME);
                    template.merge(velocityContext, stringWriter);

                    templateContent = stringWriter.toString();

                    if (templateContent.matches("(#)(\\{)([^\\}]*)(\\:)([^\\{]*)(\\})")) {
                        System.out.println("    converting # back to $");
                    }
                    templateContent = templateContent.replaceAll("(#)(\\{)([^\\}]*)(\\:)([^\\{]*)(\\})",
                            "\\$$2$3$4$5$6");
                    templateContent = templateContent.replaceAll("\\#", "#");

                    FileUtils.writeStringToFile(pfile, templateContent);
                    pfile.setLastModified(lastModified);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        Collection<File> scriptFiles = FileUtils.listFiles(
                new File(tempDir.getAbsolutePath() + "/" + JPackageManagerOld.AUTORUN_DIR_NAME),
                TEMPLATE_SUFFIX_FILE_FILTER, DirectoryFileFilter.DIRECTORY);

        if (scriptFiles != null) {
            for (File scriptfile : scriptFiles) {
                logger.debug("  processing script file: " + scriptfile.getAbsolutePath());
                try {
                    lastModified = scriptfile.lastModified();
                    templateContent = FileUtils.readFileToString(scriptfile);
                    templateContent = templateContent.replaceAll("#", "\\#");
                    templateContent = templateContent.replaceAll("(\\$)(\\{)([^\\}]*)(\\:)([^\\{]*)(\\})",
                            "#$2$3$4$5$6");

                    stringResourceRepository.putStringResource(JPackageManagerOld.CURRENT_TEMPLATE_NAME,
                            templateContent);
                    stringWriter = new StringWriter();
                    template = velocityEngine.getTemplate(JPackageManagerOld.CURRENT_TEMPLATE_NAME);
                    template.merge(velocityContext, stringWriter);

                    templateContent = stringWriter.toString();
                    templateContent = templateContent.replaceAll("(#)(\\{)([^\\}]*)(\\:)([^\\{]*)(\\})",
                            "\\$$2$3$4$5$6");
                    templateContent = templateContent.replaceAll("\\#", "#");

                    FileUtils.writeStringToFile(scriptfile, templateContent);
                    scriptfile.setLastModified(lastModified);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return status;
}

From source file:com.emc.vipr.sync.target.FilesystemTarget.java

@Override
public void filter(SyncObject obj) {
    File destFile = createFile(targetRoot.getPath(), obj.getRelativePath());
    obj.setTargetIdentifier(destFile.getPath());

    LogMF.debug(l4j, "Writing {0} to {1}", obj.getSourceIdentifier(), destFile);

    Date mtime = obj.getMetadata().getModificationTime();

    // make sure parent directory exists
    mkdirs(destFile.getParentFile());//from  w ww  . j  a  va2 s . c  om

    if (obj.isDirectory()) {
        synchronized (this) {
            if (!destFile.exists() && !destFile.mkdir())
                throw new RuntimeException("Failed to create directory " + destFile);
        }
    } else {
        // If newer or forced, copy the file data
        if (force || mtime == null || !destFile.exists() || mtime.after(new Date(destFile.lastModified()))) {
            copyData(obj, destFile);
        } else {
            LogMF.debug(l4j, "No change in content timestamps for {0}", obj.getSourceIdentifier());
        }
    }

    // encapsulate metadata from source system
    if (!ignoreMetadata) {
        File metaFile = createFile(null, SyncMetadata.getMetaPath(destFile.getPath(), destFile.isDirectory()));
        File metaDir = metaFile.getParentFile();

        Date ctime = null;
        if (obj.getMetadata() instanceof AtmosMetadata) {
            // check for ctime in system meta
            UserMetadata m = ((AtmosMetadata) obj.getMetadata()).getSystemMetadata().get("ctime");
            if (m != null)
                ctime = Iso8601Util.parse(m.getValue());
        }
        if (ctime == null)
            ctime = mtime; // use mtime if there is no ctime

        // create metadata directory if it doesn't already exist
        synchronized (this) {
            if (!metaDir.exists() && !metaDir.mkdir())
                throw new RuntimeException("Failed to create metadata directory " + metaDir);
        }

        // if *ctime* is newer or forced, write the metadata file
        if (force || ctime == null || !metaFile.exists() || ctime.after(new Date(metaFile.lastModified()))) {
            try {
                String metaJson = obj.getMetadata().toJson();
                copyData(new ByteArrayInputStream(metaJson.getBytes("UTF-8")), createOutputStream(metaFile));
                if (ctime != null) {
                    // Set the metadata file mtime to the source ctime (i.e. this
                    // metadata file's content is modified at the same
                    // time as the source's metadata modification time)
                    metaFile.setLastModified(ctime.getTime());
                }
            } catch (IOException e) {
                throw new RuntimeException("Failed to write metadata to: " + metaFile, e);
            }
        } else {
            LogMF.debug(l4j, "No change in metadata for {0}", obj.getSourceIdentifier());
        }
    }

    FilesystemUtil.applyFilesystemMetadata(destFile, obj.getMetadata(), includeAcl);
}

From source file:com.facebook.internal.FileLruCache.java

public InputStream get(String key, String contentTag) throws IOException {
    File file = new File(this.directory, Utility.md5hash(key));

    FileInputStream input = null;
    try {//from   ww  w  . j av a  2 s . c  om
        input = new FileInputStream(file);
    } catch (IOException e) {
        return null;
    }

    BufferedInputStream buffered = new BufferedInputStream(input, Utility.DEFAULT_STREAM_BUFFER_SIZE);
    boolean success = false;

    try {
        JSONObject header = StreamHeader.readHeader(buffered);
        if (header == null) {
            return null;
        }

        String foundKey = header.optString(HEADER_CACHEKEY_KEY);
        if ((foundKey == null) || !foundKey.equals(key)) {
            return null;
        }

        String headerContentTag = header.optString(HEADER_CACHE_CONTENT_TAG_KEY, null);

        if ((contentTag == null && headerContentTag != null)
                || (contentTag != null && !contentTag.equals(headerContentTag))) {
            return null;
        }

        long accessTime = new Date().getTime();
        Logger.log(LoggingBehavior.CACHE, TAG,
                "Setting lastModified to " + Long.valueOf(accessTime) + " for " + file.getName());
        file.setLastModified(accessTime);

        success = true;
        return buffered;
    } finally {
        if (!success) {
            buffered.close();
        }
    }
}

From source file:processing.app.Base.java

static public void copyFile(File sourceFile, File targetFile) throws IOException {
    InputStream from = null;/*w ww  .  j a  v a  2s . c  o  m*/
    OutputStream to = null;
    try {
        from = new BufferedInputStream(new FileInputStream(sourceFile));
        to = new BufferedOutputStream(new FileOutputStream(targetFile));
        byte[] buffer = new byte[16 * 1024];
        int bytesRead;
        while ((bytesRead = from.read(buffer)) != -1) {
            to.write(buffer, 0, bytesRead);
        }
        to.flush();
    } finally {
        IOUtils.closeQuietly(from);
        IOUtils.closeQuietly(to);
    }

    targetFile.setLastModified(sourceFile.lastModified());
}