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:WarUtil.java

/**
 * WAR???????????//w ww. j  av  a  2s  .co  m
 * 
 * @param warFile
 * @param directory
 * @throws IOException
 */
public static void extractWar(File warFile, File directory) throws IOException {
    try {
        long timestamp = warFile.lastModified();
        File warModifiedTimeFile = new File(directory, LAST_MODIFIED_FILE);
        long lastModified = readLastModifiled(warModifiedTimeFile);

        if (timestamp == lastModified) {
            //      log.info("war file " + warFile.getName() + " not modified.");
            return;
        }
        if (directory.exists()) {
            //         IOUtil.forceRemoveDirectory(directory);
            directory.mkdir();
        }

        //         log.info("war extract start. warfile=" + warFile.getName());

        JarInputStream jin = new JarInputStream(new BufferedInputStream(new FileInputStream(warFile)));
        JarEntry entry = null;

        while ((entry = jin.getNextJarEntry()) != null) {
            File file = new File(directory, entry.getName());

            if (entry.isDirectory()) {
                if (!file.exists()) {
                    file.mkdirs();
                }
            } else {
                File dir = new File(file.getParent());
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                FileOutputStream fout = null;
                try {
                    fout = new FileOutputStream(file);
                    ResourceUtil.copyStream(jin, fout);
                } finally {
                    fout.flush();
                    fout.close();
                    fout = null;
                }

                if (entry.getTime() >= 0) {
                    file.setLastModified(entry.getTime());
                }
            }
        }

        writeLastModifiled(warModifiedTimeFile, timestamp);

        //log.info("war extract success. lastmodified=" + timestamp);
    } catch (IOException ioe) {
        //log.info("war extract fail.");
        throw ioe;
    }
}

From source file:it.restrung.rest.cache.RequestCache.java

/**
 * Gets and deserializes an object from a file into its memory original representation
 *
 * @param cacheRequestInfoProvider the cache info provider
 * @param params                   the params to calculate the cache key
 * @param <T>                      the resulting type
 * @return the in memory original object
 *//*from   w ww . j a v  a  2s  . c o  m*/
public static <T extends Serializable> T get(CacheRequestInfoProvider<T> cacheRequestInfoProvider,
        Object... params) {
    File file = getCacheFile(cacheRequestInfoProvider.getContextProvider().getContext(), cacheKey(params));
    cacheRequestInfoProvider.setCacheInfo(new CacheInfo(true, new Date(file.lastModified())));
    return IOUtils.loadSerializableObjectFromDisk(file);
}

From source file:exm.stc.ui.Main.java

private static boolean olderThan(File file1, File file2) {
    long modTime1 = file1.lastModified();
    long modTime2 = file2.lastModified();
    return modTime1 < modTime2;
}

From source file:net.commerce.zocalo.freechart.ChartGenerator.java

static public boolean isFileMoreRecent(Date lastTrade, File pngFile) {
    long lastMod = pngFile.lastModified();
    return pngFile.exists() && lastMod > lastTrade.getTime();
}

From source file:net.grinder.util.LogCompressUtils.java

/**
 * Compress multiple Files with the given encoding.
 *
 * @param logFiles     files to be compressed
 * @param fromEncoding log file encoding
 * @param toEncoding   compressed log file encoding
 * @return compressed file byte array/*  w ww .j  a v a 2s  . c o m*/
 */
public static byte[] compress(File[] logFiles, Charset fromEncoding, Charset toEncoding) {
    FileInputStream fis = null;
    InputStreamReader isr = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    OutputStreamWriter osw = null;
    if (toEncoding == null) {
        toEncoding = Charset.defaultCharset();
    }
    if (fromEncoding == null) {
        fromEncoding = Charset.defaultCharset();
    }
    try {
        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        osw = new OutputStreamWriter(zos, toEncoding);
        for (File each : logFiles) {
            try {
                fis = new FileInputStream(each);
                isr = new InputStreamReader(fis, fromEncoding);
                ZipEntry zipEntry = new ZipEntry(each.getName());
                zipEntry.setTime(each.lastModified());
                zos.putNextEntry(zipEntry);
                char[] buffer = new char[COMPRESS_BUFFER_SIZE];
                int count;
                while ((count = isr.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
                    osw.write(buffer, 0, count);
                }
                osw.flush();
                zos.flush();
                zos.closeEntry();
            } catch (IOException e) {
                LOGGER.error("Error occurs while compressing {} : {}", each.getAbsolutePath(), e.getMessage());
                LOGGER.debug("Details ", e);
            } finally {
                IOUtils.closeQuietly(isr);
                IOUtils.closeQuietly(fis);
            }
        }
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.error("Error occurs while compressing log : {} ", e.getMessage());
        LOGGER.debug("Details : ", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(osw);
    }
}

From source file:fr.paris.lutece.maven.FileUtils.java

/**
 * Copy file from source to destination only if source timestamp is later
 * than the destination timestamp. The directories up to
 * <code>destination</code> will be created if they don't already exist.
 * <code>destination</code> will be overwritten if it already exists.
 *
 * @param source//from w  w  w . j  a  va 2 s .c  o m
 *            An existing non-directory <code>File</code> to copy bytes
 *            from.
 * @param destination
 *            A non-directory <code>File</code> to write bytes to
 *            (possibly overwriting).
 *
 * @throws IOException
 *             if <code>source</code> does not exist,
 *             <code>destination</code> cannot be written to, or an IO
 *             error occurs during copying.
 *
 * @throws java.io.FileNotFoundException
 *             if <code>destination</code> is a directory (use
 *             {@link #copyFileToDirectory}).
 */
public static boolean copyFileIfModified(final File source, final File destination) throws IOException {
    if (destination.lastModified() < source.lastModified()) {
        copyFile(source, destination);

        return true;
    }

    return false;
}

From source file:com.netxforge.oss2.config.HttpCollectionConfigFactory.java

/**
 * Be sure to call this method before calling getInstance().
 *
 * @throws java.io.IOException if any.//from w  w  w. ja va2 s. c o  m
 * @throws java.io.FileNotFoundException if any.
 * @throws org.exolab.castor.xml.MarshalException if any.
 * @throws org.exolab.castor.xml.ValidationException if any.
 */
public static synchronized void init()
        throws IOException, FileNotFoundException, MarshalException, ValidationException {

    if (m_instance == null) {
        File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.HTTP_COLLECTION_CONFIG_FILE_NAME);
        m_instance = new HttpCollectionConfigFactory(cfgFile.getPath());
        m_lastModified = cfgFile.lastModified();
        m_loadedFromFile = true;
    }
}

From source file:edu.ku.brc.af.core.UsageTracker.java

/**
 * Gets the installation ID that 'uniquely' identifies the running instance
 * from other installations./*www  . j a va2  s. co  m*/
 * 
 * @return the installation ID string
 */
public synchronized static String getInstallId() {
    AppPreferences appPrefs = AppPreferences.getLocalPrefs();
    if (appPrefs.isAvailable()) {

        // get the first part of the install ID
        String installIdStart = appPrefs.get("InstallIdStart", null); //$NON-NLS-1$
        if (installIdStart == null) {
            // create a new ID start (this is the first time the app has run)
            Random r = new Random(System.currentTimeMillis());
            UUID idStart = new UUID(r.nextLong(), r.nextLong());
            installIdStart = idStart.toString();
            appPrefs.put("InstallIdStart", installIdStart); //$NON-NLS-1$
        }

        // get the last part of the install ID
        String installIdEnd = appPrefs.get("InstallIdEnd", null); //$NON-NLS-1$
        File pluginRegFile = XMLHelper.getConfigDir("plugin_registry.xml"); //$NON-NLS-1$
        long lastMod = pluginRegFile.lastModified();
        String lastModString = Long.toHexString(lastMod);

        if (installIdEnd == null || !installIdEnd.equals(lastModString)) {
            // somebody must have copied this install to a new storage
            // reset the InstallIdEnd preference
            clearUsageStats();
            appPrefs.put("InstallIdEnd", lastModString); //$NON-NLS-1$
            installIdEnd = lastModString;
        }
        String installId = installIdStart + "--" + installIdEnd; //$NON-NLS-1$
        return installId;
    }
    return null;
}

From source file:Main.java

/**
 * Delete the earliest file in the specified directory
 * //from   w  w  w .  j av  a  2s  .  c  o m
 * @param dir
 *            The specified directory
 * @param exceptFile
 *            Exclude the file name
 */
public static final void deleteEarliestFile(File dir, String exceptFile) {
    if (dir != null && dir.isDirectory()) {
        File earlyFile = null;
        File[] files = dir.listFiles();
        if (files.length == 0)
            return;
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            if (f.getName().equals(exceptFile))
                continue;
            if (earlyFile == null) {
                earlyFile = files[i];
                continue;
            }
            if (earlyFile.lastModified() > f.lastModified()) {
                earlyFile = f;
            }
        }
        if (earlyFile != null)
            earlyFile.delete();
    }
}

From source file:com.googlecode.fascinator.common.storage.StorageUtils.java

/**
 * Ensure the provided harvest file is up-to-date in storage.
 * // ww w  .  java2s  .  c o m
 * @param storage a Storage instance
 * @param file to check in storage
 * @return a DigitalObject
 * @throws StorageException if the object could not be retrieved or created
 */
public static DigitalObject checkHarvestFile(Storage storage, File file) throws StorageException {
    String oid = generateOid(file);
    String lastMod = String.valueOf(file.lastModified());
    DigitalObject object;
    Properties metadata;

    try {
        // Get the object from storage
        object = storage.getObject(oid);
        try {
            // Check when it was last saved
            metadata = object.getMetadata();
            String oldMod = metadata.getProperty("lastModified");

            // Quick test - has it been changed?
            if (oldMod == null || !oldMod.equals(lastMod)) {
                // Hash the file contents
                String oldHash = metadata.getProperty("fileHash");
                String fileHash = hashFile(file);
                // Thorough test - have the contents changed?
                if (oldHash == null || !oldHash.equals(fileHash)) {
                    // Update the file
                    FileInputStream in = new FileInputStream(file);
                    object.updatePayload(object.getSourceId(), in);
                    // Update the metadata
                    metadata.setProperty("lastModified", lastMod);
                    metadata.setProperty("fileHash", fileHash);
                    // Close and return
                    object.close();
                    return object;
                }
            }
        } catch (FileNotFoundException ex1) {
            throw new StorageException("Harvest file not found: ", ex1);
        } catch (IOException ex1) {
            throw new StorageException("Error reading harvest file: ", ex1);
        } catch (StorageException ex1) {
            throw new StorageException("Error storing harvest file: ", ex1);
        }

    } catch (StorageException ex) {
        // It wasn't found in storage
        try {
            // Store it
            object = storeFile(storage, file);
            // Update its metadata
            metadata = object.getMetadata();
            metadata.setProperty("lastModified", lastMod);
            metadata.setProperty("fileHash", hashFile(file));
            // Close and return
            object.close();
            return object;
        } catch (IOException ex1) {
            throw new StorageException("Error reading harvest file: ", ex1);
        } catch (StorageException ex1) {
            throw new StorageException("Error storing harvest file: ", ex1);
        }
    }
    return null;
}