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:ezbake.frack.submitter.util.JarUtil.java

private static void add(File source, final String prefix, JarOutputStream target) throws IOException {
    BufferedInputStream in = null;
    log.debug("Adding file {} to jar", source.getName());
    try {/*from   w  w  w .java  2s  .  com*/
        String entryPath = source.getPath().replace("\\", "/").replace(prefix, "");
        if (entryPath.startsWith("/")) {
            entryPath = entryPath.substring(1);
        }
        if (source.isDirectory()) {
            if (!entryPath.isEmpty()) {
                if (!entryPath.endsWith("/")) {
                    entryPath += "/";
                }
                JarEntry entry = new JarEntry(entryPath);
                entry.setTime(source.lastModified());
                target.putNextEntry(entry);
                target.closeEntry();
            }
            for (File nestedFile : source.listFiles()) {
                add(nestedFile, prefix, target);
            }
        } else {
            JarEntry entry = new JarEntry(entryPath);
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);
            in = new BufferedInputStream(new FileInputStream(source));

            byte[] buffer = new byte[BUFFER_SIZE];
            int len;
            while ((len = in.read(buffer)) > 0) {
                target.write(buffer, 0, len);
            }
            target.closeEntry();
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:eu.sisob.uma.restserver.TaskManager.java

/**
 * // ww  w .  j ava  2 s.c  o  m
 *  Is possible that use thee locker of AuthorizationManager
 * @param user
 * @param pass
 * @param task_code
 * @param retrieveTiming 
 * @param retrieveDataUrls 
 * @param retrieveFeedback 
 * @return
 */
public static OutputTaskStatus getTaskStatus(String user, String pass, String task_code, boolean retrieveTiming,
        boolean retrieveDataUrls, boolean retrieveFeedback) {
    boolean valid = true;
    OutputTaskStatus task_status = new OutputTaskStatus();
    task_status.name = task_code;
    task_status.task_code = task_code;

    if (user != null && pass != null && task_code != null) {
        StringWriter message = new StringWriter();
        if (AuthorizationManager.validateAccess(user, pass, message)) {
            message.getBuffer().setLength(0);
            String code_task_folder = TASKS_USERS_PATH + File.separator + user + File.separator + task_code;
            File file = new File(code_task_folder);
            if (file.exists()) {
                /* Retrieve data created*/
                if (retrieveTiming) {
                    task_status.date_created = (new SimpleDateFormat("yyyy.MM.dd G - HH:mm:ss"))
                            .format(new Date(file.lastModified()));

                    File kind_file = new File(code_task_folder + File.separator + kind_flag_file);
                    if (kind_file.exists()) {
                        try {
                            task_status.kind = FileUtils.readFileToString(kind_file);
                        } catch (FileNotFoundException ex) {
                            ProjectLogger.LOGGER.error("Error, cant read " + kind_file.getAbsolutePath());
                            task_status.kind = "none";
                        } catch (IOException ex) {
                            ProjectLogger.LOGGER.error("Error, cant read " + kind_file.getAbsolutePath());
                            task_status.kind = "none";
                        }
                    } else {
                        task_status.kind = "none";
                    }
                }

                File begin_file = new File(code_task_folder + File.separator + begin_flag_file);
                if (begin_file.exists()) {
                    if (retrieveTiming) {
                        task_status.date_started = (new SimpleDateFormat("yyyy.MM.dd G - HH:mm:ss"))
                                .format(new Date(begin_file.lastModified()));
                    }

                    File end_file = new File(code_task_folder + File.separator + end_flag_file);

                    if (end_file.exists()) {
                        if (retrieveTiming) {
                            task_status.date_finished = (new SimpleDateFormat("yyyy.MM.dd G - HH:mm:ss"))
                                    .format(new Date(end_file.lastModified()));
                        }

                        valid = true;
                        task_status.status = (OutputTaskStatus.TASK_STATUS_EXECUTED);
                        task_status.message = (TheResourceBundle.getString("Jsp Task Executed Msg"));

                        if (task_status.status.equals(OutputTaskStatus.TASK_STATUS_EXECUTED)) {
                            if (retrieveDataUrls) {
                                task_status.result = "";
                                List<String> fresults = AuthorizationManager.getResultFiles(user, task_code);

                                for (String fresult : fresults) {
                                    String file_url = AuthorizationManager.getGetFileUrl(user, pass, task_code,
                                            fresult, "results");
                                    task_status.result += fresult + ";" + file_url + ";";
                                }

                                task_status.source = "";
                                List<String> fsources = AuthorizationManager.getSourceFiles(user, task_code);

                                for (String fsource : fsources) {
                                    String file_url = AuthorizationManager.getGetFileUrl(user, pass, task_code,
                                            fsource, "");
                                    task_status.source += fsource + ";" + file_url + ";";
                                }
                                //Also do method to build path
                                task_status.verbose = "";
                                List<String> fverboses = AuthorizationManager.getVerboseFiles(user, task_code);

                                for (String fverbose : fverboses) {
                                    String file_url = AuthorizationManager.getGetFileUrlToShow(user, pass,
                                            task_code, fverbose, "verbose");
                                    task_status.verbose += fverbose + ";" + file_url + ";";
                                }

                                File errors_file = new File(
                                        code_task_folder + File.separator + AuthorizationManager.results_dirname
                                                + File.separator + error_flag_file);
                                if (errors_file.exists()) {
                                    try {
                                        task_status.errors = FileUtils.readFileToString(errors_file);
                                    } catch (IOException ex) {
                                        ProjectLogger.LOGGER
                                                .error("Error, cant read " + errors_file.getAbsolutePath());
                                        task_status.errors = "Error, cant read " + errors_file.getName();
                                    }
                                }

                                File params_file = new File(
                                        code_task_folder + File.separator + params_flag_file);

                                task_status.params = "";
                                List<InputParameter> params_list = new ArrayList<InputParameter>();
                                if (params_file.exists()) {
                                    try {
                                        String params = FileUtils.readFileToString(params_file);
                                        if (!params.equals("")) {
                                            String[] lines = params.split("\r\n");

                                            for (String line : lines) {
                                                String[] values = line.split("\\$");
                                                if (values.length > 1) {
                                                    if (!task_status.params.equals(""))
                                                        task_status.params += ";";

                                                    task_status.params += values[0] + ";" + values[1];
                                                }
                                            }
                                            task_status.params = task_status.params;
                                        }

                                    } catch (IOException ex) {
                                        ProjectLogger.LOGGER
                                                .error("Error, cant read " + params_file.getAbsolutePath());
                                        task_status.errors = "Error, cant read " + params_file.getName();
                                    }
                                }
                            }

                            if (retrieveFeedback) {
                                File feedback_file = new File(
                                        code_task_folder + File.separator + AuthorizationManager.results_dirname
                                                + File.separator + feedback_flag_file);

                                String feedback = "";

                                if (feedback_file.exists()) {
                                    try {
                                        feedback = FileUtils.readFileToString(feedback_file);
                                    } catch (IOException ex) {
                                        ProjectLogger.LOGGER
                                                .error("Error, cant read " + feedback_file.getAbsolutePath());
                                    }
                                }

                                task_status.feedback = feedback;
                            }
                        }

                    } else {
                        valid = true;
                        task_status.status = (OutputTaskStatus.TASK_STATUS_EXECUTING);
                        task_status.message = (TheResourceBundle.getString("Jsp Task Executing Msg"));
                    }
                } else {
                    valid = true;
                    task_status.status = (OutputTaskStatus.TASK_STATUS_TO_EXECUTE);
                    task_status.message = (TheResourceBundle.getString("Jsp Task To Execute Msg"));
                }

            } else {
                valid = false;
                task_status.status = (OutputTaskStatus.TASK_STATUS_NO_ACCESS);
                task_status.message = (TheResourceBundle.getString("Jsp Task Unknowed Msg"));
            }
        } else {
            valid = false;
            task_status.status = (OutputTaskStatus.TASK_STATUS_NO_AUTH);
            task_status.message = message.toString();
        }
    } else {
        valid = false;
        task_status.status = (OutputTaskStatus.TASK_STATUS_NO_AUTH);
        task_status.message = (TheResourceBundle.getString("Jsp Params Invalid Msg"));
    }

    return task_status;
}

From source file:com.ms.commons.test.common.FileUtil.java

private static void doCopyDirectory(File srcDir, File destDir, boolean preserveFileDate, FileFilter filter)
        throws IOException {
    if (destDir.exists()) {
        if (destDir.isDirectory() == false) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }//from   w w  w  .j  a v a 2 s.  c  o m
    } 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++) {
        if (filter.accept(files[i])) {
            File copiedFile = new File(destDir, files[i].getName());
            if (files[i].isDirectory()) {
                doCopyDirectory(files[i], copiedFile, preserveFileDate, filter);
            } else {
                doCopyFile(files[i], copiedFile, preserveFileDate);
            }
        }
    }
}

From source file:com.wipro.ats.bdre.tdimport.FileScan.java

public static void scanAndAddToQueue() {
    try {//from   w  ww . ja v  a2  s.c  o  m
        String scanDir = TDImportRunnableMain.getMonitoredDirName();
        LOGGER.debug("Scanning directory: " + scanDir);
        File dir = new File(scanDir);
        if (!dir.exists()) {
            LOGGER.info("Created monitoring dir " + dir + " success=" + dir.mkdirs());
        }
        File arcDir = new File(scanDir + "/" + TDImportRunnableMain.ARCHIVE);
        if (!arcDir.exists()) {
            LOGGER.info("Created monitoring dir " + arcDir + " success=" + arcDir.mkdirs());
        }
        // Getting list of files recursively from directory except '_archive' directory
        Collection<File> listOfFiles = FileUtils.listFiles(dir,
                new RegexFileFilter(TDImportRunnableMain.getFilePattern()),
                new RegexFileFilter("^(?:(?!" + TDImportRunnableMain.ARCHIVE + ").)*$"));
        String fileName = "";
        FileCopyInfo fileCopyInfo = null;
        for (File file : listOfFiles) {
            fileName = file.getName();
            LOGGER.debug("Matched File Pattern by " + fileName);
            fileCopyInfo = new FileCopyInfo();
            fileCopyInfo.setFileName(fileName);
            fileCopyInfo.setSubProcessId(TDImportRunnableMain.getSubProcessId());
            LOGGER.debug("subprocessid in file scan =" + TDImportRunnableMain.getSubProcessId() + " "
                    + fileCopyInfo.getSubProcessId());
            fileCopyInfo.setSrcLocation(file.getAbsolutePath());
            fileCopyInfo.setTdTable(TDImportRunnableMain.getTdTable());
            fileCopyInfo.setFileSize(file.length());
            fileCopyInfo.setTimeStamp(file.lastModified());
            fileCopyInfo.setTdDB(TDImportRunnableMain.getTdDB());
            fileCopyInfo.setTdUserName(TDImportRunnableMain.getTdUserName());
            fileCopyInfo.setTdPassword(TDImportRunnableMain.getTdPassword());
            fileCopyInfo.setTdDelimiter(TDImportRunnableMain.getTdDelimiter());
            fileCopyInfo.setTdTpdid(TDImportRunnableMain.getTdTpdid());
            FileMonitor.addToQueue(fileName, fileCopyInfo);
        }
    } catch (Exception err) {
        LOGGER.error("Error in scan directory ", err);
        throw new BDREException(err);
    }
}

From source file:lapin.load.Loader.java

/**
 * Loads a file denoted by <code>in</code> onto the lisp environment.
 * @param in Name of the input file./*from  www.  j a v a 2  s. c om*/
 *        If a file extension is either ".lisp" or ".fasl", then this
 *        method loads a file specified by <code>in</code>.
 *        Else, the method creates two pathname
 *        <code>in + ".fasl"</code>, <code>in + ".lisp"</code>
 *        and for each pathname tests whether a file denoted by the
 *        pathname exists. If none of these files exist, then the method
 *        throws {@link lapin.io.FileException}. Else if either of these
 *        files exists (but not both), then the method loads the existing
 *        one. Else, by comparing a timestamp of these files, this method
 *        loads the newer one.
 * @param inFileEnc Character encoding for the input file.
 *        If NIL is specified, then the platform's default
 *        character encoding is used.
 * @param env
 * @return T
 * @throws lapin.io.FileException
 * @throws lapin.io.StreamException
 * @throws lapin.eval.Evaluator.Exception
 */
static public Object loadFile(String in, Object inFileEnc, Env env) {
    if (Logger.debuglevelp(env)) {
        Logger.debug("[loadFile] in: ~S", Lists.list(in), env);
        Logger.debug("[loadFile] inFileEnc: ~S", Lists.list(inFileEnc), env);
    }

    String inLisp, inFasl;
    if (in.endsWith(".lisp")) {
        inLisp = in;
        inFasl = null;
    } else if (in.endsWith(".fasl")) {
        inLisp = null;
        inFasl = in;
    } else {
        inLisp = in + ".lisp";
        inFasl = in + ".fasl";
    }

    File dir = IO.dir(Symbols.LOAD_DIR, env);

    File inFile;
    if (inLisp != null && inFasl == null)
        inFile = new File(dir, inLisp);
    else if (inLisp == null && inFasl != null)
        inFile = new File(dir, inFasl);
    else {
        File inLispFile = new File(dir, inLisp);
        File inFaslFile = new File(dir, inFasl);
        boolean inLispFileExists = inLispFile.exists();
        boolean inFaslFileExists = inFaslFile.exists();
        long inLispLastMod = inLispFileExists ? inLispFile.lastModified() : Long.MIN_VALUE;
        long inFaslLastMod = inFaslFileExists ? inFaslFile.lastModified() : Long.MIN_VALUE;
        if (inLispLastMod < inFaslLastMod) {
            inFile = inFaslFile;
        } else {
            if (inLispFileExists && inFaslFileExists)
                Logger.warn("[loadFile] ~S is older than ~S.~%" + "Loading LISP file...~%",
                        Lists.list(inFasl, inLisp), env);
            inFile = inLispFile;
        }
    }
    if (Logger.debuglevelp(env))
        Logger.debug("[loadFile] inFile=~S", Lists.list(inFile), env);

    Package currpkg = Package.get(env);
    {
        Env newenv = env.child();
        // bind Loader.MyClassLoader
        bindInternalClassLoader(newenv);
        // preserve current package
        newenv.bind(Symbols.PACKAGE, currpkg);

        InputStream inputStream = null;
        try {
            inputStream = IO.openInputStream(inFile);
            java.io.Reader r;
            r = IO.toReader(inputStream, inFileEnc);
            r = IO.wrapReader(r, Symbols.T);
            Object exp;
            while (true) {
                exp = Reader.read(r, Symbols.NIL, IO.EOF, Symbols.NIL, newenv);
                if (exp == IO.EOF) {
                    return Symbols.T;
                }
                Evaluator.eval(exp, newenv);
            }
        } finally {
            IO.close(inputStream);
        }
    }
}

From source file:com.alibaba.jstorm.ui.utils.UIUtils.java

private static boolean isFileModified(File file) {
    long lastModified = file.lastModified();
    if (uiConfigLastModified == 0 || uiConfigLastModified < lastModified) {
        uiConfigLastModified = lastModified;
        return true;
    } else {//from w  ww. j av a  2 s .  co  m
        return false;
    }
}

From source file:ai.h2o.servicebuilder.Util.java

/**
 * Create jar archive out of files list. Names in archive have paths starting from relativeToDir
 *
 * @param tobeJared     list of files/*from  www  . j  a va 2s.  c o  m*/
 * @param relativeToDir starting directory for paths
 * @return jar as byte array
 * @throws IOException
 */
public static byte[] createJarArchiveByteArray(File[] tobeJared, String relativeToDir) throws IOException {
    int BUFFER_SIZE = 10240;
    byte buffer[] = new byte[BUFFER_SIZE];
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    JarOutputStream out = new JarOutputStream(stream, new Manifest());

    for (File t : tobeJared) {
        if (t == null || !t.exists() || t.isDirectory()) {
            if (t != null && !t.isDirectory())
                logger.error("Can't add to jar {}", t);
            continue;
        }
        // Create jar entry
        String filename = t.getPath().replace(relativeToDir, "").replace("\\", "/");
        //      if (filename.endsWith("MANIFEST.MF")) { // skip to avoid duplicates
        //        continue;
        //      }
        JarEntry jarAdd = new JarEntry(filename);
        jarAdd.setTime(t.lastModified());
        out.putNextEntry(jarAdd);

        // Write file to archive
        FileInputStream in = new FileInputStream(t);
        while (true) {
            int nRead = in.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            out.write(buffer, 0, nRead);
        }
        in.close();
    }

    out.close();
    stream.close();
    return stream.toByteArray();
}

From source file:com.jaspersoft.jasperserver.war.OlapGetChart.java

/**
 * Binary streams the specified file to the HTTP response in 1KB chunks
 *
 * @param file The file to be streamed./* ww  w  . j  ava2  s .  c  o  m*/
 * @param response The HTTP response object.
 * @param mimeType The mime type of the file, null allowed.
 *
 * @throws IOException  if there is an I/O problem.
 * @throws FileNotFoundException  if the file is not found.
 */
public static void sendTempFile(File file, HttpServletResponse response, String mimeType)
        throws IOException, FileNotFoundException {

    if (file.exists()) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

        //  Set HTTP headers
        if (mimeType != null) {
            response.setHeader("Content-Type", mimeType);
        }
        response.setHeader("Content-Length", String.valueOf(file.length()));
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        response.setHeader("Last-Modified", sdf.format(new Date(file.lastModified())));

        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        byte[] input = new byte[1024];
        boolean eof = false;
        while (!eof) {
            int length = bis.read(input);
            if (length == -1) {
                eof = true;
            } else {
                bos.write(input, 0, length);
            }
        }
        bos.flush();
        bis.close();
        bos.close();
    } else {
        throw new FileNotFoundException(file.getAbsolutePath());
    }
    return;
}

From source file:com.github.chenxiaolong.dualbootpatcher.RomUtils.java

public static CacheWallpaperResult cacheWallpaper(Context context, RomInformation info, MbtoolInterface iface)
        throws IOException, MbtoolException, MbtoolCommandException {
    if (usesLiveWallpaper(info, iface)) {
        // We can't render a snapshot of a live wallpaper
        return CacheWallpaperResult.USES_LIVE_WALLPAPER;
    }//from  www.jav  a2s .c  om

    String wallpaperPath = info.getDataPath() + "/system/users/0/wallpaper";
    File wallpaperCacheFile = new File(info.getWallpaperPath());
    FileOutputStream fos = null;

    int id = -1;

    try {
        id = iface.fileOpen(wallpaperPath, new short[] {}, 0);

        // Check if we need to re-cache the file
        StatBuf sb = iface.fileStat(id);

        if (wallpaperCacheFile.exists() && wallpaperCacheFile.lastModified() / 1000 > sb.st_mtime) {
            Log.d(TAG, "Wallpaper for " + info.getId() + " has not been changed");
            return CacheWallpaperResult.UP_TO_DATE;
        }

        // Ignore large wallpapers
        if (sb.st_size < 0 || sb.st_size > 20 * 1024 * 1024) {
            return CacheWallpaperResult.FAILED;
        }

        // Read file into memory
        byte[] data = new byte[(int) sb.st_size];
        int nWritten = 0;
        while (nWritten < data.length) {
            ByteBuffer newData = iface.fileRead(id, 10240);

            int nRead = newData.limit() - newData.position();
            newData.get(data, nWritten, nRead);
            nWritten += nRead;
        }

        iface.fileClose(id);
        id = -1;

        fos = new FileOutputStream(wallpaperCacheFile);

        // Compression can be very slow (more than 10 seconds) for a large wallpaper, so we'll
        // just cache the actual file instead
        fos.write(data);

        // Load into bitmap
        //Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        //if (bitmap == null) {
        //    return false;
        //}
        //bitmap.compress(Bitmap.CompressFormat.WEBP, 100, fos);
        //bitmap.recycle();

        // Invalidate picasso cache
        Picasso.with(context).invalidate(wallpaperCacheFile);

        Log.d(TAG, "Wallpaper for " + info.getId() + " has been cached");
        return CacheWallpaperResult.UPDATED;
    } finally {
        if (id >= 0) {
            try {
                iface.fileClose(id);
            } catch (IOException e) {
                // Ignore
            }
        }
        IOUtils.closeQuietly(fos);
    }
}

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

/**
 * ?zip?solib?//w  ww.j  a  va 2 s .co  m
 *
 * @param output
 * @param srcDir
 * @throws Exception
 */
public static void addFileAndDirectoryToZip(File output, File srcDir) throws Exception {
    if (output.isDirectory()) {
        throw new IOException("This is a directory!");
    }
    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());
        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();
}