Example usage for java.io File renameTo

List of usage examples for java.io File renameTo

Introduction

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

Prototype

public boolean renameTo(File dest) 

Source Link

Document

Renames the file denoted by this abstract pathname.

Usage

From source file:BA.Server.FileUpload.java

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request/*from   w w  w .ja  va 2s. co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    PrintWriter outp = resp.getWriter();

    PrintWriter writer = null;

    try {
        writer = resp.getWriter();
    } catch (IOException ex) {
        log(FileUpload.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    StringBuffer buff = new StringBuffer();

    File file1 = (File) req.getAttribute("file");

    if (file1 == null || !file1.exists()) {
        System.out.println("File does not exist");
    } else if (file1.isDirectory()) {
        System.out.println("File is a directory");
    }

    else {
        File outputFile = new File("/tmp/" + req.getParameter("file"));
        file1.renameTo(outputFile);

        FileInputStream f = new FileInputStream(outputFile);

        // Here BufferedInputStream is added for fast reading.
        BufferedInputStream bis = new BufferedInputStream(f);
        DataInputStream dis = new DataInputStream(bis);
        int i = 0;
        String result = "";

        writer.write("<html>");
        writer.write("<head><script type='text/javascript'>");
        while (dis.available() != 0) {
            String current = dis.readLine();

            if (((String) req.getParameter("uploadType")).equals("equations")) {
                if (FormulaTester.testInput(current) == -1) {
                    writer.write("window.opener.addTabExt(\"" + current + "\" , \"" + req.getParameter("file")
                            + "\");");
                }
            } else {
                writer.write("window.opener.addMacroExt(\"" + current + "\");");
            }
            i++;

        }

        writer.write("this.close();</script></head>");
        writer.write("</script></head>");
        writer.write("<body>");
        writer.write("</body>");
        writer.write("</html>");

        writer.flush();
        writer.close();

        dis.close();
        bis.close();
        f.close();
        outputFile.delete();

    }
}

From source file:azkaban.app.JobManager.java

public void deployJobDir(String localPath, String destPath) {
    File targetPath = new File(this._jobDirs.get(0), destPath);
    verifyPathValidity(new File(localPath), targetPath);
    if (targetPath.exists()) {
        logger.info("Undeploying job at " + destPath);
        try {/*from   www  .  ja va 2s .  c  om*/
            FileUtils.deleteDirectory(targetPath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    if (!targetPath.mkdirs())
        throw new RuntimeException("Failed to create target directory " + targetPath);

    File currPath = new File(localPath);
    if (currPath.renameTo(targetPath))
        logger.info(destPath + " deployed.");
    else
        throw new RuntimeException("Deploy failed because " + currPath + " could not be moved to " + destPath);

    updateFlowManager();
}

From source file:io.druid.segment.realtime.firehose.WikipediaIrcDecoder.java

private void downloadGeoLiteDbToFile(File geoDb) {
    if (geoDb.exists()) {
        return;/* w  ww.  j a  v  a  2s . c o m*/
    }

    try {
        log.info("Downloading geo ip database to [%s]. This may take a few minutes.", geoDb.getAbsolutePath());

        File tmpFile = File.createTempFile("druid", "geo");

        FileUtils.copyInputStreamToFile(new GZIPInputStream(
                new URL("http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz")
                        .openStream()),
                tmpFile);

        if (!tmpFile.renameTo(geoDb)) {
            throw new RuntimeException("Unable to move geo file to [" + geoDb.getAbsolutePath() + "]!");
        }
    } catch (IOException e) {
        throw new RuntimeException("Unable to download geo ip database.", e);
    }
}

From source file:net.sf.jvifm.model.FileModelManager.java

private void moveFile(File srcFile, File destFile) throws IOException {

    boolean rename = srcFile.renameTo(destFile);
    if (!rename) {
        copyFile(srcFile, destFile);/*from  www . ja va 2  s. c o  m*/
        if (!srcFile.delete()) {
            FileUtils.deleteQuietly(destFile);
            throw new IOException(
                    "Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'");
        }
    }
}

From source file:br.msf.commons.util.IOUtils.java

private static File getUpdatedTarget(final File targetFile, final FileExistsAction onFileExistsAction) {
    if (targetFile == null) {
        return null;
    }//from ww w  .j  ava  2  s  . c  om
    File target = targetFile;
    final FileExistsAction action = (onFileExistsAction != null) ? onFileExistsAction
            : FileExistsAction.RENAME_NEW;
    if (target.isDirectory()) {
        throw new IllegalArgumentException("The given file already exists and is a directory.");
    } else if (target.exists()) {
        switch (action) {
        case RENAME_EXISTING:
            String tmp = target.getAbsolutePath();
            if (target.renameTo(getRenamedFile(target.getAbsolutePath(), "old"))) {
                target = new File(tmp);
            }
            break;
        case RENAME_NEW:
            target = getRenamedFile(target.getAbsolutePath(), "new");
            break;
        case THROW_EXCEPTION:
            throw new IllegalArgumentException(target.getAbsolutePath() + " already exists.");
        case OVERRIDE:
            // do nothing to the filepath
            break;
        default:
            target = null;
            break;
        }
    }
    return target;
}

From source file:com.aurel.track.attachment.AttachBL.java

/**
 * Save the attachments for new item/*from   www . j av  a 2 s .  c om*/
 * @param attachList List<TAttachmentBean>
 * @param sessionID
 * @param itemID
 */
public static List<Integer> approve(List<TAttachmentBean> attachList, String sessionID, Integer itemID) {

    if (attachList == null || attachList.isEmpty()) {
        LOGGER.debug("No attachments were stored for the new item");
        return null;
    }
    List<Integer> result = new ArrayList<Integer>(attachList.size());
    LOGGER.debug("Approve " + attachList.size() + " attachments for item#" + itemID);
    // create the directory where the attachments will be copied(renamed) to
    File newDir = new File(getFullDirName(null, itemID));
    boolean ok = newDir.mkdir();
    if (!ok) {
        LOGGER.error("Creating new attachment dir " + newDir.getAbsolutePath() + " failed!");
    }

    //ensure the disk file
    boolean parentDirOk = ensureDir(getFullDirName(null, itemID));
    if (!parentDirOk) {
        LOGGER.error("Error accessing or creating directory for attachments");
        return null;
    }

    // work through all the attachments
    Iterator<TAttachmentBean> attachIter = attachList.iterator();
    while (attachIter.hasNext()) {
        TAttachmentBean attach = attachIter.next();
        // get the old filename on disk
        String fileNameOnDiskOld = attach.getFullFileNameOnDisk();
        attach.setWorkItem(itemID);

        //save the attach in DB
        Integer attachID = save(attach);
        result.add(attachID);

        //set the fileNameOnDisk
        attach.setFullFileNameOnDisk(getFullFileName(null, attachID, itemID));
        attach.setFileNameOnDisk(getFileNameAttachment(attachID, itemID));
        String fileNameOnDiskNew = attach.getFullFileNameOnDisk();

        LOGGER.debug("Rename " + fileNameOnDiskOld + " to " + fileNameOnDiskNew);
        // rename all the attachments
        File fileOld = new File(fileNameOnDiskOld);
        File fileNew = new File(fileNameOnDiskNew);
        ok = fileOld.renameTo(fileNew);
        if (!ok) {
            LOGGER.error(
                    "Renaming " + fileOld.getAbsolutePath() + " to " + fileNew.getAbsolutePath() + " failed!");
        }
    }
    // remove the old temp-directory
    deleteTempFiles(sessionID);
    return result;
}

From source file:net.sf.jclal.experiment.ExperimentBuilder.java

/**
 * Expands the experiments for the configuration file
 *
 * @param experimentFileName The name of the experiment file.
 * @return The experiments for the configuration file.
 *//*  w ww.j  ava 2  s  .co m*/
public ArrayList<String> buildExperiment(String experimentFileName) {
    ArrayList<String> configurations = expandElements(experimentFileName);
    ArrayList<String> allCreatedExperiments = new ArrayList<String>();
    int numberExperiments = 1;

    allCreatedExperiments.addAll(configurations);

    /**
     * Expand multi-valued elements
     */
    do {
        numberExperiments = configurations.size();

        ArrayList<String> createdExperiments = new ArrayList<String>();

        for (String experiment : configurations) {
            createdExperiments.addAll(expandElements(experiment));
        }

        allCreatedExperiments.addAll(createdExperiments);

        configurations = createdExperiments;

    } while (configurations.size() != numberExperiments);

    /**
     * Expand multi-valued attributes
     */
    do {
        numberExperiments = configurations.size();

        ArrayList<String> createdExperiments = new ArrayList<String>();

        for (String experiment : configurations) {
            createdExperiments.addAll(expandAttributes(experiment));
        }

        allCreatedExperiments.addAll(createdExperiments);

        configurations = createdExperiments;

    } while (configurations.size() != numberExperiments);

    allCreatedExperiments.removeAll(configurations);

    /**
     * Remove temp files
     */
    for (String temp : allCreatedExperiments) {
        if (!temp.equals(experimentFileName)) {
            new File(temp).delete();
        }
    }

    /**
     * Move the expanded configuration files to the experiments folder
     */
    if (configurations.size() > 1) {
        File dir = new File("experiments");

        /**
         * If the directory exists, delete all files
         */
        if (dir.exists()) {
            File[] experimentFiles = dir.listFiles();
            for (File f : experimentFiles) {
                f.delete();
            }
        } /**
          * Else, create the directory
          */
        else {
            dir.mkdir();
        }

        for (int i = 0; i < configurations.size(); i++) {
            File file = new File(configurations.get(i));
            file.renameTo(new File(dir, file.getName()));
            String[] files = configurations.get(i).split("/");
            String fileName = files[files.length - 1];
            configurations.set(i, dir.getPath() + "/" + fileName);
        }
    }
    /**
     * Return the configuration filenames
     */
    return configurations;
}

From source file:com.owncloud.android.operations.DownloadFileOperation.java

@Override
protected RemoteOperationResult run(WebdavClient client) {
    RemoteOperationResult result = null;
    File newFile = null;/*from   w w  w  .  ja v  a 2  s  .c om*/
    boolean moved = true;

    /// download will be performed to a temporal file, then moved to the final location
    File tmpFile = new File(getTmpPath());

    /// perform the download
    try {
        tmpFile.getParentFile().mkdirs();
        int status = downloadFile(client, tmpFile);
        if (isSuccess(status)) {
            newFile = new File(getSavePath());
            newFile.getParentFile().mkdirs();
            moved = tmpFile.renameTo(newFile);
        }
        if (!moved)
            result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
        else
            result = new RemoteOperationResult(isSuccess(status), status,
                    (mGet != null ? mGet.getResponseHeaders() : null));
        Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": "
                + result.getLogMessage());

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG,
                "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage(),
                e);
    }

    return result;
}

From source file:org.apache.hadoop.gateway.GatewayDeployFuncTest.java

private File writeTestTopology(String name, XMLTag xml) throws IOException {
    // Create the test topology.
    File tempFile = new File(config.getGatewayTopologyDir(), name + ".xml." + UUID.randomUUID());
    FileOutputStream stream = new FileOutputStream(tempFile);
    xml.toStream(stream);//from www  .  j  a  v a  2 s.  co  m
    stream.close();
    File descriptor = new File(config.getGatewayTopologyDir(), name + ".xml");
    tempFile.renameTo(descriptor);
    return descriptor;
}

From source file:net.codestory.simplelenium.driver.Downloader.java

protected void downloadZip(String driverName, String url, File targetZip) {
    if (targetZip.exists()) {
        if (targetZip.length() > 0) {
            return;
        }//from ww  w  .jav a  2  s .c  om
        targetZip.delete();
    }

    System.out.printf("Downloading %s from %s...%n", driverName, url);

    File zipTemp = new File(targetZip.getAbsolutePath() + ".temp");
    zipTemp.getParentFile().mkdirs();

    try (InputStream input = URI.create(url).toURL().openStream()) {
        Files.copy(input, zipTemp.toPath());
    } catch (IOException e) {
        throw new IllegalStateException(
                "Unable to download " + driverName + " from " + url + " to " + targetZip, e);
    }

    if (!zipTemp.renameTo(targetZip)) {
        throw new IllegalStateException(String.format("Unable to rename %s to %s", zipTemp.getAbsolutePath(),
                targetZip.getAbsolutePath()));
    }
}