Example usage for java.io File lastModified

List of usage examples for java.io File lastModified

Introduction

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

Prototype

public long lastModified() 

Source Link

Document

Returns the time that the file denoted by this abstract pathname was last modified.

Usage

From source file:com.moviejukebox.scanner.AttachmentScanner.java

/**
 * Extract an attachment//  w w  w .  j av  a2s  .c om
 *
 * @param attachment the attachment to extract
 * @param setImage true, if a set image should be extracted; in this case ".set" is append before file extension
 * @param counter a counter (only used for NFOs cause there may be multiple NFOs in one file)
 * @return
 */
private static File extractAttachment(Attachment attachment) {
    File sourceFile = attachment.getSourceFile();
    if (sourceFile == null) {
        // source file must exist
        return null;
    } else if (!sourceFile.exists()) {
        // source file must exist
        return null;
    }

    // build return file name
    StringBuilder returnFileName = new StringBuilder();
    returnFileName.append(tempDirectory.getAbsolutePath());
    returnFileName.append(File.separatorChar);
    returnFileName.append(FilenameUtils.removeExtension(sourceFile.getName()));
    // add attachment id so the extracted file becomes unique per movie file
    returnFileName.append(".");
    returnFileName.append(attachment.getAttachmentId());

    switch (attachment.getContentType()) {
    case NFO:
        returnFileName.append(".nfo");
        break;
    case POSTER:
    case FANART:
    case BANNER:
    case SET_POSTER:
    case SET_FANART:
    case SET_BANNER:
    case VIDEOIMAGE:
        returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType()));
        break;
    default:
        returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType()));
        break;
    }

    File returnFile = new File(returnFileName.toString());
    if (returnFile.exists() && (returnFile.lastModified() >= sourceFile.lastModified())) {
        // already present or extracted
        LOG.debug("File to extract already exists; no extraction needed");
        return returnFile;
    }

    LOG.trace("Extract attachement ({})", attachment);
    try {
        // Create the command line
        List<String> commandMedia = new ArrayList<>(MT_EXTRACT_EXE);
        commandMedia.add("attachments");
        commandMedia.add(sourceFile.getAbsolutePath());
        commandMedia.add(attachment.getAttachmentId() + ":" + returnFileName.toString());

        ProcessBuilder pb = new ProcessBuilder(commandMedia);
        pb.directory(MT_PATH);
        Process p = pb.start();

        if (p.waitFor() != 0) {
            LOG.error("Error during extraction - ErrorCode={}", p.exitValue());
            returnFile = null;
        }
    } catch (IOException | InterruptedException ex) {
        LOG.error(SystemTools.getStackTrace(ex));
        returnFile = null;
    }

    if (returnFile != null) {
        if (returnFile.exists()) {
            // need to reset last modification date to last modification date
            // of source file to fulfill later checks
            try {
                returnFile.setLastModified(sourceFile.lastModified());
            } catch (Exception ignore) {
                // nothing to do anymore
            }
        } else {
            // reset return file to null if not existent
            returnFile = null;
        }
    }
    return returnFile;
}

From source file:gov.nasa.ensemble.common.io.FileUtilities.java

/**
 * recursive last modified method/*w  w w  .  j a v a2s  .c  o  m*/
 * 
 * @param file
 * @return Date
 */
public static Date getLastModified(File file) {
    Date date = null;
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        for (File currentFile : files) {
            Date currentLastModifiedDate = getLastModified(currentFile);
            if (date == null || (currentLastModifiedDate != null && date.before(currentLastModifiedDate))) {
                date = currentLastModifiedDate;
            }
        }
    } else {
        date = new Date(file.lastModified());
    }
    return date;
}

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");
    }//w w  w  .j av  a2 s .  c  o m

    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:net.adamcin.oakpal.testing.TestPackageUtil.java

private static void add(final File root, final File source, final JarOutputStream target) throws IOException {
    if (root == null || source == null) {
        throw new IllegalArgumentException("Cannot add from a null file");
    }/* www  . j a  v a2s  .  c  o  m*/
    if (!(source.getPath() + "/").startsWith(root.getPath() + "/")) {
        throw new IllegalArgumentException("source must be the same file or a child of root");
    }
    final String relPath;
    if (!root.getPath().equals(source.getPath())) {
        relPath = source.getPath().substring(root.getPath().length() + 1).replace(File.separator, "/");
    } else {
        relPath = "";
    }
    if (source.isDirectory()) {
        if (!relPath.isEmpty()) {
            String name = relPath;
            if (!name.endsWith("/")) {
                name += "/";
            }
            JarEntry entry = new JarEntry(name);
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);
            target.closeEntry();
        }
        File[] children = source.listFiles();
        if (children != null) {
            for (File nestedFile : children) {
                add(root, nestedFile, target);
            }
        }
    } else {
        JarEntry entry = new JarEntry(relPath);
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        try (InputStream in = new BufferedInputStream(new FileInputStream(source))) {
            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        }
    }
}

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.
 *///from ww w. jav a  2 s  . co 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.meltmedia.cadmium.core.FileSystemManager.java

public static void copyAllContent(final String source, final String target, final boolean ignoreHidden)
        throws Exception {
    File sourceFile = new File(source);
    File targetFile = new File(target);
    if (!targetFile.exists()) {
        targetFile.mkdirs();// w w w.j  av  a2 s.c om
    }
    if (sourceFile.exists() && sourceFile.canRead() && sourceFile.isDirectory() && targetFile.exists()
            && targetFile.canWrite() && targetFile.isDirectory()) {
        List<File> copyList = new ArrayList<File>();
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File file, String name) {
                return !ignoreHidden || !name.startsWith(".");
            }

        };
        File files[] = sourceFile.listFiles(filter);
        if (files.length > 0) {
            copyList.addAll(Arrays.asList(files));
        }
        for (int index = 0; index < copyList.size(); index++) {
            File aFile = copyList.get(index);
            String relativePath = aFile.getAbsoluteFile().getAbsolutePath()
                    .replaceFirst(sourceFile.getAbsoluteFile().getAbsolutePath(), "");
            if (aFile.isDirectory()) {
                File newDir = new File(target, relativePath);
                if (newDir.mkdir()) {
                    newDir.setExecutable(aFile.canExecute(), false);
                    newDir.setReadable(aFile.canRead(), false);
                    newDir.setWritable(aFile.canWrite(), false);
                    newDir.setLastModified(aFile.lastModified());
                    files = aFile.listFiles(filter);
                    if (files.length > 0) {
                        copyList.addAll(index + 1, Arrays.asList(files));
                    }
                } else {
                    log.warn("Failed to create new subdirectory \"{}\" in the target path \"{}\".",
                            relativePath, target);
                }
            } else {
                File newFile = new File(target, relativePath);
                if (newFile.createNewFile()) {
                    FileInputStream inStream = null;
                    FileOutputStream outStream = null;
                    try {
                        inStream = new FileInputStream(aFile);
                        outStream = new FileOutputStream(newFile);
                        streamCopy(inStream, outStream);
                    } finally {
                        if (inStream != null) {
                            try {
                                inStream.close();
                            } catch (Exception e) {
                            }
                        }
                        if (outStream != null) {
                            try {
                                outStream.flush();
                            } catch (Exception e) {
                            }
                            try {
                                outStream.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                    newFile.setExecutable(aFile.canExecute(), false);
                    newFile.setReadable(aFile.canRead(), false);
                    newFile.setWritable(aFile.canWrite(), false);
                    newFile.setLastModified(aFile.lastModified());
                }
            }
        }
    }
}

From source file:net.sf.zekr.engine.template.ZekrFileResourceLoader.java

public long getLastModified(Resource resource) {
    File file = new File(resource.getName());
    return file.canRead() ? file.lastModified() : 0;
}

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

public static boolean configure(File tempDir, File localConfigurationFile) {
    logger.info("PackageManager::configure()");
    boolean status = true;
    if (tempDir != null && localConfigurationFile != null) {
        Configuration configuration = null;
        try {//  w w  w  . j  a  v  a 2 s. c o m
            configuration = new PropertiesConfiguration(localConfigurationFile);
        } catch (ConfigurationException ce) {
            //dont want to error out completely if config file is not loaded
            ce.printStackTrace();
        }

        if (configuration != null && !configuration.isEmpty()) {
            Map<String, String> substitutionContext = JPackageManager.createSubstitutionContext(configuration);
            StrSubstitutor strSubstitutor = new StrSubstitutor(substitutionContext);
            String templateContent = null;
            long lastModified;

            Collection<File> patchFiles = FileUtils.listFiles(
                    new File(tempDir.getAbsolutePath() + "/" + JPackageManager.PATCH_DIR_NAME + "/"
                            + JPackageManager.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);
                        templateContent = strSubstitutor.replace(templateContent);
                        FileUtils.writeStringToFile(pfile, templateContent);
                        pfile.setLastModified(lastModified);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            Collection<File> scriptFiles = FileUtils.listFiles(
                    new File(tempDir.getAbsolutePath() + "/" + JPackageManager.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 = strSubstitutor.replace(templateContent);
                        FileUtils.writeStringToFile(scriptfile, templateContent);
                        scriptfile.setLastModified(lastModified);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return status;
}

From source file:com.alibaba.zonda.logger.server.util.DirectoryListener.java

public List<File> list(File startDirectory, String filterRegex) throws IOException {
    List<File> dirList = new ArrayList<File>();
    walk(startDirectory, dirList);//from ww  w.  jav  a2  s  . c  om
    Collections.sort(dirList, new Comparator<File>() {
        public int compare(File f1, File f2) {
            return (Long.valueOf(f1.lastModified())).compareTo(Long.valueOf(f2.lastModified()));
        }
    });
    List<File> filteredDirList = new ArrayList<File>();
    for (File f : dirList) {
        if (f.getName().matches(filterRegex)) {
            filteredDirList.add(f);
        }
    }
    return filteredDirList;
}

From source file:org.opendatakit.common.android.utilities.ODKFileUtils.java

/**
 * Recursively traverse the directory to find the most recently modified
 * file within it./*  w ww  .ja va 2  s .c  o  m*/
 *
 * @param formDir
 * @return lastModifiedDate of the most recently modified file.
 */
public static long getMostRecentlyModifiedDate(File formDir) {
    long lastModifiedDate = formDir.lastModified();
    Iterator<File> allFiles = FileUtils.iterateFiles(formDir, null, true);
    while (allFiles.hasNext()) {
        File f = allFiles.next();
        if (f.lastModified() > lastModifiedDate) {
            lastModifiedDate = f.lastModified();
        }
    }
    return lastModifiedDate;
}