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.taobao.android.builder.tools.zip.ZipUtils.java

public static void addFileAndDirectoryToZip(File output, File srcDir, Map<String, ZipEntry> zipEntryMethodMap)
        throws Exception {
    if (output.isDirectory()) {
        throw new IOException("This is a directory!");
    }/*from  www .  ja  v a  2s.  c  om*/
    if (!output.getParentFile().exists()) {
        output.getParentFile().mkdirs();
    }

    if (!output.exists()) {
        output.createNewFile();
    }
    List fileList = getSubFiles(srcDir);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(output));
    ZipEntry ze = null;
    byte[] buf = new byte[1024];
    int readLen = 0;
    for (int i = 0; i < fileList.size(); i++) {
        File f = (File) fileList.get(i);
        ze = new ZipEntry(getAbsFileName(srcDir.getPath(), f));
        ze.setSize(f.length());
        ze.setTime(f.lastModified());
        if (zipEntryMethodMap != null) {
            ZipEntry originEntry = zipEntryMethodMap.get(f.getAbsolutePath());
            if (originEntry != null) {
                ze.setCompressedSize(originEntry.getCompressedSize());
                ze.setCrc(originEntry.getCrc());
                ze.setMethod(originEntry.getMethod());
            }
        }
        zos.putNextEntry(ze);
        InputStream is = new BufferedInputStream(new FileInputStream(f));
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            zos.write(buf, 0, readLen);
        }
        is.close();
    }
    zos.close();
}

From source file:com.moviejukebox.tools.SkinProperties.java

/**
 * Read the skin information from skinVersionFilename in the skin directory
 *//*from www.  jav  a2s .com*/
public static void readSkinVersion() {
    String skinVersionPath = StringTools.appendToPath(SKIN_HOME, SKIN_VERSION_FILENAME);
    File xmlFile = new File(skinVersionPath);

    if (xmlFile.exists()) {
        LOG.debug("Scanning file '{}'", xmlFile.getAbsolutePath());
    } else {
        LOG.debug("{} does not exist, skipping", xmlFile.getAbsolutePath());
        return;
    }

    try {
        XMLConfiguration xmlConfig = new XMLConfiguration(xmlFile);
        setSkinName(xmlConfig.getString("name"));
        setSkinVersion(xmlConfig.getString("version"));
        setSkinDate(xmlConfig.getString("date"));
        setSkinMessage(StringTools.castList(String.class, xmlConfig.getList("message")));
        setFileDate(xmlFile.lastModified());
    } catch (ConfigurationException error) {
        LOG.error("Failed reading version information file '{}'", SKIN_VERSION_FILENAME);
        LOG.warn(SystemTools.getStackTrace(error));
    }
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

public static void rezip(File output, File srcDir, Map<String, ZipEntry> zipEntryMethodMap) throws Exception {
    if (output.isDirectory()) {
        throw new IOException("This is a directory!");
    }/*from   w  w w  . ja va2 s. c  o  m*/
    if (!output.getParentFile().exists()) {
        output.getParentFile().mkdirs();
    }

    if (!output.exists()) {
        output.createNewFile();
    }
    List fileList = getSubFiles(srcDir);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(output));
    ZipEntry ze = null;
    byte[] buf = new byte[1024];
    int readLen = 0;
    for (int i = 0; i < fileList.size(); i++) {
        File f = (File) fileList.get(i);
        ze = new ZipEntry(getAbsFileName(srcDir.getPath(), f));
        ze.setSize(f.length());
        ze.setTime(f.lastModified());
        if (zipEntryMethodMap != null) {
            ZipEntry originEntry = zipEntryMethodMap.get(ze.getName());
            if (originEntry != null) {
                if (originEntry.getMethod() == STORED) {
                    ze.setCompressedSize(f.length());
                    InputStream in = new BufferedInputStream(new FileInputStream(f));
                    try {
                        CRC32 crc = new CRC32();
                        int c;
                        while ((c = in.read()) != -1) {
                            crc.update(c);
                        }
                        ze.setCrc(crc.getValue());
                    } finally {
                        in.close();
                    }
                }
                ze.setMethod(originEntry.getMethod());
            }
        }
        zos.putNextEntry(ze);
        InputStream is = new BufferedInputStream(new FileInputStream(f));
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            zos.write(buf, 0, readLen);
        }
        is.close();
    }
    zos.close();
}

From source file:de.rallye.config.RallyeConfig.java

/**
 * Read Config from Config File if present
 * @return Found Config File or Default Config
 *//*from   ww  w.j ava 2 s.c  om*/
public static RallyeConfig fromFile(File configFile, GitRepositoryState git) {
    RallyeConfig config;

    if (configFile == null) {
        logger.error("No config file found.");
        return null;
    }
    logger.info("Loading config file from {}", configFile);
    ObjectMapper mapper = new ObjectMapper();
    try {
        config = mapper.readValue(configFile, RallyeConfig.class);
        File parent = configFile.getParentFile();
        if (parent != null)
            config.configFileDir = parent + File.separator;
        else
            config.configFileDir = "";

        config.lastModified = configFile.lastModified();

        if (git != null) {
            config.setGit(git);
            logger.info("Current Build:\n\t{}", git);
        }

        return config;
    } catch (IOException e) {
        logger.error("Config invalid.", e);
        return null;
    }
}

From source file:net.paissad.waqtsalat.utils.geoip.GeoipHelper.java

/**
 * Verify whether or not an update is available for the specified GEOIP
 * resource.//  w w  w  .  jav  a  2  s. c  o  m
 * <p>
 * <b>Note</b>:If the local file does not exist yet, then an update is
 * supposed to be automatically available.
 * </p>
 * 
 * @param type
 * @param localFile
 *            - The local file to use while comparing timestamps.
 * @return <tt>true</tt> if an update is available, <tt>false</tt>
 *         otherwise.
 * 
 * @see GEOIPTYPE
 */
public static boolean isUpdateAvailable(GEOIPTYPE type, final File localFile) {

    /*
     * TODO: instead of relying on the presence and timestamp of the local
     * file, the datas should be stored into a database. It's safer.
     * In other words, the timestamp of 'eventual' previous dates of updates
     * should be saved into a database/table.
     */

    logger.info("Checking GeoIP update for {}.", type.toString());
    String url = null;
    if (type == GEOIPTYPE.DATABASE) {
        url = GEOIP_DATABASE_UPDATE_URL;
    } else if (type == GEOIPTYPE.WORLD_CITIES) {
        url = GEOIP_WORLDCITIES_URL;
    }

    if (!localFile.exists()) {
        return true;
    }

    Date localDate = new Date(localFile.lastModified());
    Date remoteDate = new Date(CommonUtils.getRemoteTimestamp(url));

    return remoteDate.after(localDate);
}

From source file:hudson.ClassicPluginStrategy.java

/**
 * Explodes the plugin into a directory, if necessary.
 *///from   w w w  .ja  v a  2 s.  co m
private static void explode(File archive, File destDir) throws IOException {
    destDir.mkdirs();

    // timestamp check
    File explodeTime = new File(destDir, ".timestamp2");
    if (explodeTime.exists() && explodeTime.lastModified() == archive.lastModified())
        return; // no need to expand

    // delete the contents so that old files won't interfere with new files
    Util.deleteRecursive(destDir);

    try {
        Project prj = new Project();
        unzipExceptClasses(archive, destDir, prj);
        createClassJarFromWebInfClasses(archive, destDir, prj);
    } catch (BuildException x) {
        throw new IOException("Failed to expand " + archive, x);
    }

    try {
        new FilePath(explodeTime).touch(archive.lastModified());
    } catch (InterruptedException e) {
        throw new AssertionError(e); // impossible
    }
}

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

public static boolean configure(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 ww  . j a  v a2 s . c o  m*/
        Template template = null;
        VelocityContext velocityContext = JPackageManagerBU.createVelocityContext(configuration);
        StringResourceRepository stringResourceRepository = StringResourceLoader.getRepository();
        String templateContent = null;
        StringWriter stringWriter = null;
        long lastModified;

        Collection<File> patchFiles = FileUtils.listFiles(
                new File(tempDir.getAbsolutePath() + "/" + JPackageManagerBU.PATCH_DIR_NAME + "/"
                        + JPackageManagerBU.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 = templateContent.replaceAll("(\\$)(\\{)([^\\}]*)(\\:)([^\\}]*)(\\})",
                            "#$2$3$4$5$6");

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

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

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

        Collection<File> scriptFiles = FileUtils.listFiles(
                new File(tempDir.getAbsolutePath() + "/" + JPackageManagerBU.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("(\\$)(\\{)([^\\}]*)(\\:)([^\\}]*)(\\})",
                            "#$2$3$4$5$6");

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

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

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

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

From source file:msi.gama.application.workspace.WorkspaceModelsManager.java

public static String getCurrentGamaStampString() {
    String gamaStamp = null;/* w  ww.  j  a  v a  2  s  .co m*/
    try {
        final URL tmpURL = new URL("platform:/plugin/msi.gama.models/models/");
        final URL new_url = FileLocator.resolve(tmpURL);
        final String path_s = new_url.getPath().replaceFirst("^/(.:/)", "$1");
        final java.nio.file.Path normalizedPath = Paths.get(path_s).normalize();
        final File modelsRep = normalizedPath.toFile();

        // loading file from URL Path is not a good idea. There are some bugs
        // File modelsRep = new File(urlRep.getPath());

        final long time = modelsRep.lastModified();
        gamaStamp = ".built_in_models_" + time;
        System.out.println(">GAMA version " + WorkspaceModelsManager.BUILTIN_VERSION + " loading...");
        System.out.println(">GAMA models library version: " + gamaStamp);
    } catch (final IOException e) {
        e.printStackTrace();
    }
    return gamaStamp;
}

From source file:edu.ku.brc.specify.tasks.subpane.JasperReportsCache.java

/**
 * Starts the report creation process/*from  w w  w.java 2 s. com*/
 * @param fileName the XML file name of the report definition
 * @param recrdSet the recordset to use to fill the labels
 */
public static ReportCompileInfo checkReport(final File file) {
    File cachePath = getCachePath();
    String fileName = file.getName();
    File compiledPath = getCompiledFile(file);

    AppResourceIFace appRes = AppContextMgr.getInstance().getResource(fileName);

    File reportFileFromCache = new File(cachePath.getAbsoluteFile() + File.separator + fileName);

    // Check to see if it needs to be recompiled, if it doesn't need compiling then
    // call "compileComplete" directly to have it start filling the labels
    // otherswise create the compiler runnable and have it be compiled 
    // asynchronously

    Timestamp apTime = appRes.getTimestampModified() == null ? appRes.getTimestampCreated()
            : appRes.getTimestampModified();
    boolean needsCompiling = apTime == null || !compiledPath.exists()
            || apTime.getTime() > reportFileFromCache.lastModified();

    //log.debug(appRes.getTimestampModified().getTime()+" > "+reportFileFromCache.lastModified() +"  "+(appRes.getTimestampModified().getTime() > reportFileFromCache.lastModified()));
    //log.debug(compiledPath.exists());
    //log.debug("needsCompiling "+needsCompiling);
    return new ReportCompileInfo(reportFileFromCache, compiledPath, needsCompiling);
}

From source file:FileStatus.java

public static void status(String fileName) throws IOException {
    System.out.println("---" + fileName + "---");

    // Construct a File object for the given file.
    File f = new File(fileName);

    // See if it actually exists
    if (!f.exists()) {
        System.out.println("file not found");
        System.out.println(); // Blank line
        return;/* w w w . j  a  v  a  2  s.  c o  m*/
    }
    // Print full name
    System.out.println("Canonical name " + f.getCanonicalPath());
    // Print parent directory if possible
    String p = f.getParent();
    if (p != null) {
        System.out.println("Parent directory: " + p);
    }
    // Check if the file is readable
    if (f.canRead()) {
        System.out.println("File is readable.");
    }
    // Check if the file is writable
    if (f.canWrite()) {
        System.out.println("File is writable.");
    }
    // Report on the modification time.
    Date d = new Date();
    d.setTime(f.lastModified());
    System.out.println("Last modified " + d);

    // See if file, directory, or other. If file, print size.
    if (f.isFile()) {
        // Report on the file's size
        System.out.println("File size is " + f.length() + " bytes.");
    } else if (f.isDirectory()) {
        System.out.println("It's a directory");
    } else {
        System.out.println("I dunno! Neither a file nor a directory!");
    }

    System.out.println(); // blank line between entries
}