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:org.java.plugin.standard.ShadingPathResolver.java

static void unpack(final ZipFile zipFile, final File destFolder) throws IOException {
    for (Enumeration en = zipFile.entries(); en.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) en.nextElement();
        String name = entry.getName();
        File entryFile = new File(destFolder.getCanonicalPath() + "/" + name); //$NON-NLS-1$
        if (name.endsWith("/")) { //$NON-NLS-1$
            if (!entryFile.exists() && !entryFile.mkdirs()) {
                throw new IOException("can't create folder " + entryFile); //$NON-NLS-1$
            }/*from  ww w  . j a  va 2 s  . co m*/
        } else {
            File folder = entryFile.getParentFile();
            if (!folder.exists() && !folder.mkdirs()) {
                throw new IOException("can't create folder " + folder); //$NON-NLS-1$
            }
            OutputStream out = new BufferedOutputStream(new FileOutputStream(entryFile, false));
            try {
                InputStream in = zipFile.getInputStream(entry);
                try {
                    IoUtil.copyStream(in, out, 1024);
                } finally {
                    in.close();
                }
            } finally {
                out.close();
            }
        }
        entryFile.setLastModified(entry.getTime());
    }
}

From source file:org.datavaultplatform.common.io.FileCopy.java

/**
 * Internal copy file method.//from w  w w  . j a va 2s .  c  om
 * 
 * @param progress  the progress tracking object
 * @param srcFile  the validated source file, must not be {@code null}
 * @param destFile  the validated destination file, must not be {@code null}
 * @param preserveFileDate  whether to preserve the file date
 * @throws IOException if an error occurs
 */
private static void doCopyFile(Progress progress, File srcFile, File destFile, boolean preserveFileDate)
        throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    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;
        while (pos < size) {
            count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
            long copied = output.transferFrom(input, pos, count);
            pos += copied;
            progress.byteCount += copied;
            progress.timestamp = System.currentTimeMillis();
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fis);
    }

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

    progress.fileCount += 1;
}

From source file:org.apache.drill.exec.store.parquet.TestPushDownAndPruningForDecimal.java

private String createTable(String tableName, boolean removeMetadata) throws IOException {
    File rootDir = dirTestWatcher.getRootDir();
    File tablePath = new File(rootDir, String.format("%s_%s", tableName, UUID.randomUUID()));
    FileUtils.copyDirectory(fileStore, tablePath);
    File metadata = new File(tablePath, ".drill.parquet_metadata");
    if (removeMetadata) {
        assertTrue(metadata.delete());/*from  w w w  . ja v  a 2  s.  c om*/
    } else {
        // metadata modification time should be higher
        // than directory modification time otherwise metadata file will be regenerated
        assertTrue(metadata.setLastModified(Instant.now().toEpochMilli()));
    }
    String table = String.format("dfs.`root`.`%s`", tablePath.getName());
    tablesToDrop.add(table);
    return table;
}

From source file:org.eclipse.aether.transport.http.HttpTransporterTest.java

@Test
public void testGet_ResumeLocalContentsOutdated() throws Exception {
    File file = TestFileUtils.createTempFile("re");
    file.setLastModified(System.currentTimeMillis() - 5 * 60 * 1000);
    RecordingTransportListener listener = new RecordingTransportListener();
    GetTask task = new GetTask(URI.create("repo/resume.txt")).setDataFile(file, true).setListener(listener);
    transporter.get(task);//ww w  .  j  av  a 2  s  .  com
    assertEquals("resumable", TestFileUtils.readString(file));
    assertEquals(1L, listener.startedCount);
    assertEquals(0L, listener.dataOffset);
    assertEquals(9, listener.dataLength);
    assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0);
    assertEquals("resumable", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8));
}

From source file:org.isatools.isatab.export.isatab.filesdispatching.ISATabExportRepoFilesChecker.java

/**
 * Process all files that results non referenced, ie they're not in {@link #referencedFiles}, after that this was
 * computed by {@link #collectReferredFiles(AssayGroup, Mode)}. For these files issues a warning and also
 * copies them on a backup location, if mode == {@link Mode#BACKUP}.
 *///from   w w  w.ja v  a2s .co m
private void processOrphanFiles(final AssayGroup ag, Mode mode) throws IOException {
    if (ag == null) {
        return;
    }

    SectionInstance assaySectionInstance = ag.getAssaySectionInstance();
    if (assaySectionInstance == null) {
        log.warn("I cannot find any record in the DB for the file: " + ag.getFilePath() + ", hope it's fine");
        return;
    }

    Study study = ag.getStudy();

    // TODO: generic
    for (AnnotationTypes targetType : AnnotationTypes.DATA_PATH_ANNOTATIONS) {
        String dataLocationPath = StringUtils.trimToNull(
                dataLocationMgr.getDataLocation(study, ag.getMeasurement(), ag.getTechnology(), targetType));
        if (dataLocationPath == null) {
            continue;
        }
        File dataLocationDir = new File(dataLocationPath);
        dataLocationPath = dataLocationDir.getCanonicalPath();
        if (!dataLocationDir.isDirectory() && !dataLocationDir.canRead() && !dataLocationDir.canWrite()) {
            log.warn("Directory '" + dataLocationPath + "' is not accessible, skipping it");
            continue;
        }

        log.debug("Checking unreferenced files into '" + dataLocationPath + "'");

        Collection<File> existingFiles = FileUtils.listFiles(dataLocationDir, null, true);
        for (File existingFile : existingFiles) {
            if (this.referencedFiles.containsKey(existingFile)) {
                continue;
            }
            String existingPath = existingFile.getCanonicalPath();

            log.warn("WARNING: The file '" + existingPath
                    + "' is no longer referred by the exported submission");
            if (mode != Mode.BACKUP) {
                continue;
            }

            String backupPath = dataLocationPath + "/original";
            log.warn("Moving it to the backup location: '" + backupPath + "'");
            String fileRelPath = existingPath.substring(dataLocationPath.length() + 1);
            String backupFilePath = backupPath + "/" + fileRelPath;
            File backupFile = new File(backupFilePath);

            if (backupFile.exists() && backupFile.lastModified() == existingFile.lastModified()) {
                log.debug("Not copying " + existingPath + "' to '" + backupFilePath
                        + "': they seem to be the same.");
                continue;
            }
            log.trace("Copying data file '" + existingPath + "' / '" + backupFilePath
                    + "' to data repository...");
            FileUtils.moveFile(existingFile, backupFile);
            // Needed cause of a bug in the previous function
            backupFile.setLastModified(existingFile.lastModified());
            log.trace("...done");

            // Do it only once
            this.referencedFiles.put(existingFile, "");
        }
    }

}

From source file:com.adito.boot.Util.java

/**
 * Copy a file to another file./* ww  w. ja v a  2 s . c o m*/
 * 
 * @param f file to copy
 * @param t target file
 * @param onlyIfNewer only copy if the target file is new
 * @throws IOException on any error
 */
public static void copy(File f, File t, boolean onlyIfNewer) throws IOException {
    if (!onlyIfNewer || f.lastModified() > t.lastModified()) {
        if (log.isDebugEnabled())
            log.debug("Copying " + f.getAbsolutePath() + " to " + t.getAbsolutePath());
        InputStream in = new FileInputStream(f);
        try {
            OutputStream out = new FileOutputStream(t);
            try {
                copy(in, out);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
        t.setLastModified(f.lastModified());
    } else {
        if (log.isDebugEnabled())
            log.debug("Skipping copying of file " + f.getAbsolutePath()
                    + " as the target is newer than the source.");
    }
}

From source file:fr.opensagres.xdocreport.document.tools.remoting.resources.FileUtils.java

/**
 * Internal copy directory method./*from   w w  w.  java2 s.  c o m*/
 * 
 * @param srcDir  the validated source directory, must not be <code>null</code>
 * @param destDir  the validated destination directory, must not be <code>null</code>
 * @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() == false) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }
    } else {
        if (destDir.mkdirs() == false) {
            throw new IOException("Destination '" + destDir + "' directory cannot be created");
        }
        if (preserveFileDate) {
            destDir.setLastModified(srcDir.lastModified());
        }
    }
    if (destDir.canWrite() == false) {
        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:cn.com.sinosoft.util.io.FileUtils.java

/**
 * Implements the same behaviour as the "touch" utility on Unix. It creates
 * a new file with size 0 or, if the file exists already, it is opened and
 * closed without modifying it, but updating the file date and time.
 * <p>//from   w w w  . ja  va2 s .c o m
 * NOTE: As from v1.3, this method throws an IOException if the last
 * modified date of the file cannot be set. Also, as from v1.3 this method
 * creates parent directories if they do not exist.
 *
 * @param file  the File to touch
 * @throws IOException If an I/O problem occurs
 */
public static void touch(File file) throws IOException {
    if (!file.exists()) {
        OutputStream out = openOutputStream(file);
        IOUtils.closeQuietly(out);
    }
    boolean success = file.setLastModified(System.currentTimeMillis());
    if (!success) {
        throw new IOException("Unable to set the last modification time for " + file);
    }
}

From source file:de.jwi.jfm.Folder.java

private void fileCopy(File source, File target) throws IOException {
    FileInputStream in = new FileInputStream(source);
    FileOutputStream out = new FileOutputStream(target);
    int c;//from w w  w  . j  a  va2  s.c  o m

    try {
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        target.setLastModified(source.lastModified());
    } finally {
        out.close();
        in.close();
    }
}

From source file:org.eclipse.aether.transport.http.HttpTransporterTest.java

@Before
public void setUp() throws Exception {
    System.out.println("=== " + testName.getMethodName() + " ===");
    session = TestUtils.newSession();/*from  w  w w .  java 2 s.  co m*/
    factory = new HttpTransporterFactory();
    repoDir = TestFileUtils.createTempDir();
    TestFileUtils.writeString(new File(repoDir, "file.txt"), "test");
    TestFileUtils.writeString(new File(repoDir, "dir/file.txt"), "test");
    TestFileUtils.writeString(new File(repoDir, "empty.txt"), "");
    TestFileUtils.writeString(new File(repoDir, "some space.txt"), "space");
    File resumable = new File(repoDir, "resume.txt");
    TestFileUtils.writeString(resumable, "resumable");
    resumable.setLastModified(System.currentTimeMillis() - 90 * 1000);
    httpServer = new HttpServer().setRepoDir(repoDir).start();
    newTransporter(httpServer.getHttpUrl());
}