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:com.puppetlabs.geppetto.forge.util.TarUtils.java

/**
 * Unpack the content read from <i>source</i> into <i>targetFolder</i>. If the
 * <i>skipTopFolder</i> is set, then don't assume that the archive contains one
 * single folder and unpack the content of that folder, not including the folder
 * itself.//from   www .  j  a  v  a  2s .  c  o  m
 * 
 * @param source
 *            The input source. Must be in <i>TAR</i> format.
 * @param targetFolder
 *            The destination folder for the unpack. Not used when a <tt>fileCatcher</tt> is provided
 * @param skipTopFolder
 *            Set to <code>true</code> to unpack beneath the top folder
 *            of the archive. The archive must consist of one single folder and nothing else
 *            in order for this to work.
 * @param fileCatcher
 *            Used when specific files should be picked from the archive without writing them to disk. Can be
 *            <tt>null</tt>.
 * @throws IOException
 */
public static void unpack(InputStream source, File targetFolder, boolean skipTopFolder, FileCatcher fileCatcher)
        throws IOException {
    String topFolderName = null;
    Map<File, Map<Integer, List<String>>> chmodMap = new HashMap<File, Map<Integer, List<String>>>();
    TarArchiveInputStream in = new TarArchiveInputStream(source);
    try {
        TarArchiveEntry te = in.getNextTarEntry();
        if (te == null) {
            throw new IOException("No entry in the tar file");
        }
        do {
            if (te.isGlobalPaxHeader())
                continue;

            String name = te.getName();
            if (skipTopFolder) {
                int firstSlash = name.indexOf('/');
                if (firstSlash < 0)
                    throw new IOException("Archive doesn't contain one single folder");

                String tfName = name.substring(0, firstSlash);
                if (topFolderName == null)
                    topFolderName = tfName;
                else if (!tfName.equals(topFolderName))
                    throw new IOException("Archive doesn't contain one single folder");
                name = name.substring(firstSlash + 1);
            }
            if (name.length() == 0)
                continue;

            String linkName = te.getLinkName();
            if (linkName != null) {
                if (linkName.trim().equals(""))
                    linkName = null;
            }

            if (fileCatcher != null) {
                if (linkName == null && !te.isDirectory() && fileCatcher.accept(name)) {
                    if (fileCatcher.catchData(name, in))
                        // We're done here
                        return;
                }
                continue;
            }

            File outFile = new File(targetFolder, name);
            if (linkName != null) {
                if (!OsUtil.link(targetFolder, name, te.getLinkName()))
                    throw new IOException("Archive contains links but they are not supported on this platform");
            } else {
                if (te.isDirectory()) {
                    outFile.mkdirs();
                } else {
                    outFile.getParentFile().mkdirs();
                    OutputStream target = new FileOutputStream(outFile);
                    StreamUtil.copy(in, target);
                    target.close();
                    outFile.setLastModified(te.getModTime().getTime());
                }
                registerChmodFile(chmodMap, targetFolder, Integer.valueOf(te.getMode()), name);
            }
        } while ((te = in.getNextTarEntry()) != null);
    } finally {
        StreamUtil.close(in);
    }
    chmod(chmodMap);
}

From source file:phex.util.FileUtils.java

/**
 * From Apache Jakarta Commons IO.//  ww  w.j av a 2  s.  c  om
 * <p>
 * Internal copy directory method.
 *
 * @param srcDir           the validated source directory, not null
 * @param destDir          the validated destination directory, not null
 * @param preserveFileDate whether to preserve the file date
 * @throws IOException if an error occurs
 * @since Commons IO 1.1
 */
private static void doCopyDirectory(File srcDir, File destDir, boolean preserveFileDate) throws IOException {
    if (destDir.exists()) {
        if (!destDir.isDirectory()) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }
    } else {
        forceMkdir(destDir);
        if (preserveFileDate) {
            destDir.setLastModified(srcDir.lastModified());
        }
    }
    if (!destDir.canWrite()) {
        throw new IOException("Destination '" + destDir + "' cannot be written to");
    }
    // recurse
    File[] files = srcDir.listFiles();
    if (files == null) { // null if security restricted
        throw new IOException("Failed to list contents of " + srcDir);
    }
    for (int i = 0; i < files.length; i++) {
        File copiedFile = new File(destDir, files[i].getName());
        if (files[i].isDirectory()) {
            doCopyDirectory(files[i], copiedFile, preserveFileDate);
        } else {
            doCopyFile(files[i], copiedFile, preserveFileDate);
        }
    }
}

From source file:com.dvlcube.cuber.utils.FileUtils.java

private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }/*from  w ww  .j av  a  2 s .  com*/

    FileInputStream input = new FileInputStream(srcFile);
    try {
        FileOutputStream output = new FileOutputStream(destFile);
        try {
            IOUtils.copy(input, output);
        } finally {
            IOUtils.closeQuietly(output);
        }
    } finally {
        IOUtils.closeQuietly(input);
    }

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

From source file:com.google.dart.tools.update.core.internal.UpdateUtils.java

/**
 * Copy a file from one place to another, providing progress along the way.
 *///www .j a  v a  2s .  c  o m
public static void copyFile(File fromFile, File toFile, IProgressMonitor monitor) throws IOException {

    byte[] data = new byte[4096];

    InputStream in = new FileInputStream(fromFile);

    toFile.delete();

    OutputStream out = new FileOutputStream(toFile);

    int count = in.read(data);

    while (count != -1) {
        out.write(data, 0, count);
        count = in.read(data);
    }

    in.close();
    out.close();

    toFile.setLastModified(fromFile.lastModified());
    if (fromFile.canExecute()) {
        toFile.setExecutable(true);
    }

    monitor.worked(1);

}

From source file:com.thalesgroup.hudson.plugins.copyarchiver.FilePathArchiver.java

/**
 * Reads from a tar stream and stores obtained files to the base dir.
 * @param isFlatten true if flatten// www .jav  a  2s.  c  o  m
 * @param name the name
 * @param baseDir the base directory
 * @param in the inputstream
 * @throws IOException the IOException
 */
@SuppressWarnings("unchecked")
private static void readFromTar(boolean isFlatten, String name, File baseDir, InputStream in)
        throws IOException {
    TarInputStream t = new TarInputStream(in);
    try {
        TarEntry te;
        while ((te = t.getNextEntry()) != null) {

            File f = new File(baseDir, te.getName());
            if (te.isDirectory()) {
                if (!isFlatten)
                    f.mkdirs();
            } else {
                if (!isFlatten) {
                    File parent = f.getParentFile();
                    if (parent != null)
                        parent.mkdirs();
                } else {
                    f = new File(baseDir, getFileNameWithoutLeadingDirectory(te.getName()));
                }

                OutputStream fos = new FileOutputStream(f);
                try {
                    IOUtils.copy(t, fos);
                } finally {
                    fos.close();
                }
                f.setLastModified(te.getModTime().getTime());
                int mode = te.getMode() & 0777;
                if (mode != 0 && !Functions.isWindows()) // be defensive
                    try {
                        LIBC.chmod(f.getPath(), mode);
                    } catch (NoClassDefFoundError e) {
                        // be defensive. see http://www.nabble.com/-3.0.6--Site-copy-problem%3A-hudson.util.IOException2%3A--java.lang.NoClassDefFoundError%3A-Could-not-initialize-class--hudson.util.jna.GNUCLibrary-td23588879.html
                    }
            }

        }
    } catch (IOException e) {
        throw new IOException2("Failed to extract " + name, e);
    } finally {
        t.close();
    }
}

From source file:org.sakaiproject.search.util.FileUtils.java

/**
 * unpack a segment from a zip//from   www .j a  va  2  s.  c om
 * 
 * @param addsi
 * @param packetStream
 * @param version
 */
public static void unpack(InputStream source, File destination) throws IOException {
    ZipInputStream zin = new ZipInputStream(source);
    ZipEntry zipEntry = null;
    FileOutputStream fout = null;
    try {
        byte[] buffer = new byte[4096];
        while ((zipEntry = zin.getNextEntry()) != null) {

            long ts = zipEntry.getTime();
            // the zip entry needs to be a full path from the
            // searchIndexDirectory... hence this is correct

            File f = new File(destination, zipEntry.getName());
            if (log.isDebugEnabled())
                log.debug("         Unpack " + f.getAbsolutePath());
            if (!f.getParentFile().exists()) {
                if (!f.getParentFile().mkdirs()) {
                    log.warn("unpack(): Failed to create parent folder: " + f.getParentFile().getPath());
                }
            }

            fout = new FileOutputStream(f);
            int len;
            while ((len = zin.read(buffer)) > 0) {
                fout.write(buffer, 0, len);
            }
            zin.closeEntry();
            fout.close();
            if (!f.setLastModified(ts)) {
                log.warn("upack(): failes to set modified date on " + f.getPath());
            }
        }
    } finally {
        try {
            fout.close();
        } catch (Exception ex) {
            log.warn("Exception closing file output stream", ex);
        }
    }
}

From source file:com.amazonaws.eclipse.core.accounts.profiles.SdkCredentialsFileContentMonitorTest.java

private void touch(File file) {
    file.setLastModified(System.currentTimeMillis() / 1000);
}

From source file:com.jaeksoft.searchlib.ClientCatalog.java

public static final void receive_file(Client client, String filePath, long lastModified, InputStream is)
        throws IOException {
    File rootDir = getTempReceiveDir(client);
    File targetFile = new File(rootDir, filePath);
    targetFile.createNewFile();/*w w w  . ja v  a  2s. c  om*/
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(targetFile);
        int len;
        byte[] buffer = new byte[131072];
        while ((len = is.read(buffer)) != -1)
            fos.write(buffer, 0, len);
    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.close(fos);
    }
    targetFile.setLastModified(lastModified);
}

From source file:org.red5.io.FileKeyFrameMetaCacheTest.java

@Test
public void testSerialization() throws IOException {
    FileKeyFrameMetaCache cache = new FileKeyFrameMetaCache();
    File f = File.createTempFile("red5", "MetaCacheTest");
    f.setLastModified(1481275039000L);
    KeyFrameMeta meta = new KeyFrameMeta();
    meta.positions = new long[] { -666, 0, 666 };
    meta.timestamps = new int[] { 0, 666, 666 * 2 };
    cache.saveKeyFrameMeta(f, meta);//  w  w w . j a va 2  s.  c  o m
    try (InputStreamReader ir1 = new InputStreamReader(
            FileKeyFrameMetaCacheTest.class.getResourceAsStream("Red5MetaCacheTest1.xml"),
            StandardCharsets.UTF_8); FileReader fr2 = new FileReader(f.getCanonicalPath() + ".meta")) {
        Assert.assertTrue("Generated file has bad contents", IOUtils.contentEqualsIgnoreEOL(ir1, fr2));
    }
}

From source file:com.github.brandtg.switchboard.FileLogIndexer.java

@Override
public void start() throws Exception {
    fileLogWatcher.register(Paths.get(config.getRootDir()));
    executorService.submit(fileLogWatcher);

    // Touch all files to ensure that they're indexed
    File[] files = new File(config.getRootDir()).listFiles();
    if (files != null) {
        for (File file : files) {
            if (file.setLastModified(System.currentTimeMillis())) {
                LOG.info("Touched {} to initiate indexing", file);
            } else {
                LOG.warn("Failed to touch {}, index may be inaccurate!", file);
            }//w  ww.  ja  va  2 s. c o m
        }
    }

    LOG.info("Started file log indexer");
}