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.appeligo.showfiles.FilesByTime.java

/**
 * @param request/*  www . j av a 2 s  .  c  o m*/
 * @param out
 * @param path
 */
private void listFiles(HttpServletRequest request, PrintWriter out, String path, int limit) {
    header(out);
    Comparator<File> comparator = new Comparator<File>() {
        public int compare(File leftFile, File rightFile) {
            long leftMod = leftFile.lastModified();
            long rightMod = rightFile.lastModified();
            if (leftMod < rightMod) {
                return -1;
            } else if (leftMod > rightMod) {
                return 1;
            } else {
                return leftFile.getPath().compareTo(rightFile.getPath());
            }
        }
    };
    SortedSet<File> fileSet = new TreeSet<File>(comparator);
    addFile(fileSet, new File(path));

    log.info("Total files in tree is " + fileSet.size());

    if (limit > 0 && fileSet.size() > limit) {
        log.info("Trimming tree to limit " + limit);
        Iterator<File> iter = fileSet.iterator();
        int toDrop = fileSet.size() - limit;
        for (int i = 0; i < toDrop; i++) {
            iter.next();
        }
        File first = iter.next();
        fileSet = fileSet.tailSet(first);
    }

    int suggestedLimit = 1000;
    if (limit == 0 && fileSet.size() > suggestedLimit) {
        out.println("That's a lot of files!  There are " + fileSet.size() + " files to return.<br/>");
        out.println("How about just the <a href=\"" + request.getRequestURI() + "?" + suggestedLimit
                + "\">last " + suggestedLimit + "</a>.<br/>");
        out.println("If you really want them all, <a href=\"" + request.getRequestURI() + "?"
                + (fileSet.size() + suggestedLimit) + "\">click here</a>.<br/>");
    } else {

        DateFormat dateFormat = SimpleDateFormat.getDateInstance();
        DateFormat timeFormat = SimpleDateFormat.getTimeInstance();
        Calendar lastDay = Calendar.getInstance();
        Calendar day = Calendar.getInstance();
        boolean first = true;

        for (File file : fileSet) {
            Date fileDate = new Date(file.lastModified());
            day.setTime(fileDate);
            if (first || lastDay.get(Calendar.DAY_OF_YEAR) != day.get(Calendar.DAY_OF_YEAR)) {
                out.print("<b>" + dateFormat.format(fileDate) + "</b><br/>");
            }
            String servlet = "/ShowFile";
            if (file.getPath().endsWith(".flv")) {
                servlet = "/ShowFlv";
            }
            out.print(timeFormat.format(fileDate) + " <a href=\"" + request.getContextPath() + servlet
                    + file.getPath().substring(documentRoot.length()) + "\">" + file.getPath() + "</a>");
            out.println("<br/>");
            lastDay.setTime(fileDate);
            first = false;
        }
    }
    footer(out);
}

From source file:com.tc.websocket.runners.TempFileMonitor.java

@Override
public void run() {

    if (TaskRunner.getInstance().isClosing()) {
        return;/*from   w  ww .  j a va 2s . co  m*/
    }

    try {
        File temp = File.createTempFile("temp", "temp");
        String absolutePath = temp.getAbsolutePath();
        String tempFilePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));

        System.out.println("cleaning out directory " + tempFilePath);

        File tempdir = new File(tempFilePath);
        File[] files = tempdir.listFiles();

        temp.delete();//cleanup

        if (files != null) {
            for (File file : files) {
                String name = file.getName();
                if (file.exists() && name.startsWith("eo") && name.endsWith("tm")) {
                    //calculate the age
                    Date lastmod = new Date(file.lastModified());
                    long minutes = DateUtils.getTimeDiffMin(lastmod, new Date());
                    if (minutes >= 5) {
                        FileUtils.deleteQuietly(file);
                    }
                }
            }
        }
    } catch (Exception e) {
        LOG.log(Level.SEVERE, null, e);
    }
}

From source file:com.yunmall.ymsdk.net.http.AsyncHttpRequest.java

private CacheData loadCache(ResponseHandlerInterface responseHandlerInterface) {
    String cacheFileName = responseHandlerInterface.getCacheFileName();
    if (TextUtils.isEmpty(cacheFileName)) {
        return null;
    }/*from   w ww .j a v  a  2 s  . c o m*/
    CacheData cacheData = new CacheData();
    File file = new File(cacheFileName);
    cacheData.time = file.lastModified();
    if (!file.exists()) {
        return null;
    }

    long fileSize = file.length();
    if (fileSize == 0) {
        clearCache(cacheFileName);
        return null;
    }

    long time = System.currentTimeMillis() - cacheData.time;
    if (time > AsyncHttpClient.DEFAULT_CACHE_EXPIRATION_TIME) {
        clearCache(cacheFileName);
        return null;
    }
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        byte[] fileData = new byte[(int) fileSize];
        if (fis.read(fileData) != fileSize) {
            clearCache(cacheFileName);
            return null;
        }

        if (fileData.length <= 0) {
            clearCache(cacheFileName);
            return null;
        }
        cacheData.cacheData = fileData;
        return cacheData;

    } catch (OutOfMemoryError e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
        clearCache(cacheFileName);
    } finally {
        try {
            if (fis != null) {
                fis.close();
                fis = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.jaeksoft.searchlib.crawler.cache.LocalFileCrawlCache.java

@Override
public DownloadItem load(URI uri, long expirationTime) throws IOException, JSONException, URISyntaxException {
    rwl.r.lock();//  ww w.j  ava 2  s. com
    try {
        File file = uriToFile(uri, META_EXTENSION);
        if (!file.exists())
            return null;
        if (expirationTime != 0)
            if (file.lastModified() < expirationTime)
                return null;
        String content = FileUtils.readFileToString(file);
        JSONObject json = new JSONObject(content);
        DownloadItem downloadItem = new DownloadItem(uri);
        downloadItem.loadMetaFromJson(json);
        file = uriToFile(uri, CONTENT_EXTENSION);
        downloadItem.setContentInputStream(new FileInputStream(file));
        return downloadItem;
    } finally {
        rwl.r.unlock();
    }
}

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

/**
 * <p>update</p>//from  w  w w.  j  ava2s. co m
 *
 * @throws java.io.IOException if any.
 * @throws org.exolab.castor.xml.MarshalException if any.
 * @throws org.exolab.castor.xml.ValidationException if any.
 */
public synchronized void update() throws IOException, MarshalException, ValidationException {

    File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.SNMP_INTERFACE_POLLER_CONFIG_FILE_NAME);
    if (cfgFile.lastModified() > m_currentVersion) {
        m_currentVersion = cfgFile.lastModified();
        logStatic().debug("init: config file path: " + cfgFile.getPath());
        InputStream stream = null;
        try {
            stream = new FileInputStream(cfgFile);
            reloadXML(stream);
        } finally {
            if (stream != null) {
                IOUtils.closeQuietly(stream);
            }
        }
        logStatic().debug("init: finished loading config file: " + cfgFile.getPath());
    }
}

From source file:MainClass.java

public void setFileStats(File dir) {
    String files[] = dir.list();//from   w  ww  .  j a  va 2  s .  com
    data = new Object[files.length][titles.length];

    for (int i = 0; i < files.length; i++) {
        File tmp = new File(files[i]);
        data[i][0] = new Boolean(tmp.isDirectory());
        data[i][1] = tmp.getName();
        data[i][2] = new Boolean(tmp.canRead());
        data[i][3] = new Boolean(tmp.canWrite());
        data[i][4] = new Long(tmp.length());
        data[i][5] = new Date(tmp.lastModified());
    }

    fireTableDataChanged();
}

From source file:com.servoy.extension.install.CopyZipEntryImporter.java

protected void enforceBackUpFolderLimit() {
    // limit backup folder size to 1 GB; although it's hudge, it's there just not to cause HDD problems because of un-called for backups
    final int MAX = 1024 * 1024 * 1024;

    File backUpFolder = new File(installDir + File.separator + BACKUP_FOLDER);
    if (backUpFolder.exists() && backUpFolder.isDirectory()) {
        long size = FileUtils.sizeOfDirectory(backUpFolder);
        if (size > MAX) {
            // delete oldest files first
            long sizeOverflow = size - MAX;
            List<File> sortedByDate = new SortedList<File>(new Comparator<File>() {
                public int compare(File o1, File o2) {
                    long result = o1.lastModified() - o2.lastModified();
                    return (result < 0) ? -1 : (result == 0 ? 0 : 1);
                }/*from w w w . j  a  v  a 2 s. co  m*/
            });
            sortedByDate.addAll(Arrays.asList(backUpFolder.listFiles()));
            for (File f : sortedByDate) {
                sizeOverflow -= FileUtils.sizeOf(f);
                FileUtils.deleteQuietly(f);
                if (f.exists())
                    sizeOverflow += FileUtils.sizeOf(f);

                if (sizeOverflow < 0)
                    break;
            }
        }
    }
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.sensitivity.ResultFileEvaluator.java

@Override
public void run(CommandLine commandLine) throws Exception {
    ResultFileReader reader = null;/*from w w w. j  a va2  s  .  c o m*/
    MetricFileWriter writer = null;
    Problem problem = null;
    NondominatedPopulation referenceSet = null;

    File inputFile = new File(commandLine.getOptionValue("input"));
    File outputFile = new File(commandLine.getOptionValue("output"));

    // sanity check to ensure input hasn't been modified after the output
    if (!commandLine.hasOption("force") && (outputFile.lastModified() > 0L)
            && (inputFile.lastModified() > outputFile.lastModified())) {
        throw new FrameworkException("input appears to be newer than output");
    }

    // load reference set and create the quality indicator
    if (commandLine.hasOption("reference")) {
        referenceSet = new NondominatedPopulation(
                PopulationIO.readObjectives(new File(commandLine.getOptionValue("reference"))));
    } else {
        referenceSet = ProblemFactory.getInstance().getReferenceSet(commandLine.getOptionValue("problem"));
    }

    if (referenceSet == null) {
        throw new FrameworkException("no reference set available");
    }

    // open the resources and begin processing
    try {
        // setup the problem
        if (commandLine.hasOption("problem")) {
            problem = ProblemFactory.getInstance().getProblem(commandLine.getOptionValue("problem"));
        } else {
            problem = new ProblemStub(Integer.parseInt(commandLine.getOptionValue("dimension")));
        }

        QualityIndicator indicator = new QualityIndicator(problem, referenceSet);

        try {
            reader = new ResultFileReader(problem, inputFile);

            try {
                writer = new MetricFileWriter(indicator, outputFile);

                // resume at the last good output
                for (int i = 0; i < writer.getNumberOfEntries(); i++) {
                    if (reader.hasNext()) {
                        reader.next();
                    } else {
                        throw new FrameworkException("output has more entries than input");
                    }
                }

                // evaluate the remaining entries
                while (reader.hasNext()) {
                    writer.append(reader.next());
                }
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    } finally {
        if (problem != null) {
            problem.close();
        }
    }
}

From source file:eu.openanalytics.rsb.data.FileResultStore.java

private PersistedResult buildPersistedResult(final String applicationName, final String userName,
        final UUID jobId, final File resultFile) {
    final GregorianCalendar resultTime = (GregorianCalendar) GregorianCalendar.getInstance();
    resultTime.setTimeInMillis(resultFile.lastModified());

    final boolean success = !StringUtils.contains(resultFile.getName(), ERROR_FILE_INFIX_EXTENSION + ".");
    final MimeType mimeType = Util.getMimeType(resultFile);

    return new PersistedResult(applicationName, userName, jobId, resultTime, success, mimeType) {
        @Override/*from   ww  w.  j a  v a 2  s. c  om*/
        public InputStream getData() {
            try {
                return new FileInputStream(resultFile);
            } catch (final FileNotFoundException fnfe) {
                throw new IllegalStateException(fnfe);
            }
        }

        @Override
        public long getDataLength() {
            return resultFile.length();
        }
    };
}

From source file:at.treedb.util.Compress.java

/**
 * Adds an empty directory to the archive.
 * /*  ww w.ja  va 2  s  . c o m*/
 * @param dir
 *            empty directory
 * @throws IOException
 */
private void addEmptyDir(File dir) throws IOException {
    SevenZArchiveEntry entry = new SevenZArchiveEntry();
    entry.setName(dir.getAbsolutePath().substring(baseDir.length()).replace('\\', '/'));
    entry.setAccessDate(dir.lastModified());
    entry.setCreationDate(dir.lastModified());
    entry.setLastModifiedDate(dir.lastModified());
    entry.setDirectory(true);
    sevenZOutput.putArchiveEntry(entry);
    sevenZOutput.closeArchiveEntry();

}