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:org.paxml.table.csv.CsvTable.java

private void renameFiles() throws IOException {
    File file = res.getFile();
    if (needToWrite) {
        if (log.isDebugEnabled()) {
            log.debug("Writing csv file: " + file.getAbsolutePath());
        }/*w w  w .j  a  v a 2s. c  om*/
        File del = null;
        if (file.exists()) {
            File f = res.getFile();
            del = PaxmlUtils.getSiblingFile(f, "." + seq.getNextValue(f.getAbsolutePath()) + ".delete", true);
            if (!file.renameTo(del)) {
                if (log.isErrorEnabled()) {
                    log.error("Cannot rename csv file '" + f.getAbsolutePath() + "' to '"
                            + del.getAbsolutePath() + "'");
                }
                throw new PaxmlRuntimeException("Cannot overwrite csv file: " + getResourceIdentifier());
            }

        }
        if (!writerFile.renameTo(file)) {
            if (log.isErrorEnabled()) {
                log.error("Cannot rename csv file '" + writerFile.getAbsolutePath() + "' to '"
                        + file.getAbsolutePath() + "'");
            }
            throw new PaxmlRuntimeException("Cannnot overwrite csv file: " + getResourceIdentifier());
        }
        if (del != null) {
            del.delete();
            if (log.isWarnEnabled()) {
                log.warn("Cannot delete shadow csv file: " + del.getAbsolutePath());
            }
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("No need to write to csv file: " + file.getAbsolutePath());
        }
        if (!writerFile.delete()) {
            if (log.isWarnEnabled()) {
                log.warn("Cannot delete shadow csv file: " + writerFile.getAbsolutePath());
            }
        }
    }
}

From source file:com.nuvolect.securesuite.webserver.connector.CmdUpload.java

/**
 * Collect chunk data until last chuck is received, then assemble the uploaded file.
 *
 * EXAMPLE, 60.3MB file:/*w  w w . j a v a  2 s . c  o  m*/
 * "cmd" -> "upload"
 * "mtime[]" -> "1489684754"
 * "cid" -> "697767115"
 * "upload_path[]" -> "l0_L3Rlc3QvdG1w"
 * "range" -> "0,10485760,60323475"
 x "post_uploads" -> "[{"file_path":"\/data\/user\/0\/com.nuvolect.securesuite.debug\/cache\/NanoHTTPD-340250228","file_name":"blob"}]"
 * "dropWith" -> "0"
 * "chunk" -> "kepler_7_weeks.mp4.0_5.part"
 x "target" -> "l0_L3Rlc3QvdG1w"
 * "unique_id" -> "1489174097708"
 * "upload[]" -> "blob"
 * "queryParameterStrings" -> "cmd=ls&target=l0_L3Rlc3QvdG1w&intersect%5B%5D=kepler_7_weeks.mp4&_=1489697705506"
 * "uri" -> "/connector"
 */
private InputStream chunksUpload(@NonNull Map<String, String> params, OmniFile targetDirectory) {
    String url = params.get("url");
    String targetVolumeId = targetDirectory.getVolumeId();

    JsonObject wrapper = new JsonObject();
    String chunk = params.get("chunk");
    String[] parts = chunk.split(Pattern.quote("."));
    String[] twoNumbers = parts[parts.length - 2].split("_");
    int chunkMax = Integer.valueOf(twoNumbers[1]);
    String targetFilename = parts[0] + "." + parts[1];
    JsonObject fileChunks = new JsonObject(); // Chunks for the target file

    /**
     * Parse the uploads array and collect specific of the current chunk.
     * Metadata for each chunk is saved in a JSONObject using the chunk filename as the key.
     * Move each chunk from the app:/cache folder to app:/chunk.
     * When all chunks are uploaded, the target is assembled and chunks deleted.
     */
    JsonParser parser = new JsonParser();
    JsonArray postUploads = parser.parse(params.get("post_uploads")).getAsJsonArray();

    for (int i = 0; i < postUploads.size(); i++) {
        JsonObject postUpload = postUploads.get(i).getAsJsonObject();
        //app: /cache/xxx
        String cachePath = postUpload.get(CConst.FILE_PATH).getAsString();
        File cacheFile = new File(cachePath);

        String chunkPath = chunkDirPath + FilenameUtils.getName(cachePath);
        File chunkFile = new File(chunkPath);

        /**
         * Move the chunk, otherwise Nanohttpd will delete it.
         */
        cacheFile.renameTo(chunkFile);

        JsonObject chunkObj = new JsonObject();
        chunkObj.addProperty("filepath", chunkPath);
        chunkObj.addProperty("range", params.get("range"));

        if (fileUploads.has(targetFilename)) {
            fileChunks = fileUploads.get(targetFilename).getAsJsonObject();
        } else {
            fileChunks = new JsonObject();
        }
        fileChunks.add(chunk, chunkObj);
        fileUploads.add(targetFilename, fileChunks);
    }

    /**
     * If not complete, return with intermediate results
     */
    if (fileChunks.size() <= chunkMax) {
        wrapper.add("added", new JsonArray());

        return getInputStream(wrapper);
    }

    try {
        int totalSize = 0;
        /**
         * All chunks are uploaded.  Iterate over the chunk meta data and assemble the file.
         * Open the target file.
         */
        OmniFile destFile = new OmniFile(targetVolumeId,
                targetDirectory.getPath() + File.separator + targetFilename);
        OutputStream destOutputStream = destFile.getOutputStream();
        String error = null;

        for (int i = 0; i <= chunkMax; i++) {
            String chunkKey = targetFilename + "." + i + "_" + chunkMax + ".part";

            if (!fileChunks.has(chunk)) {
                error = "Missing chunk: " + chunkKey;
                break;
            }

            JsonObject chunkObj = fileChunks.get(chunkKey).getAsJsonObject();
            String chunkPath = chunkObj.get("filepath").getAsString();
            File sourceFile = new File(chunkPath);
            if (sourceFile.exists()) {
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File exists: " + sourceFile.getPath());
            } else {
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File NOT exists: " + sourceFile.getPath());
                break;
            }

            FileInputStream fis = new FileInputStream(sourceFile);

            //TODO error check range of bytes from each chunk and compare with chunk bytes copied

            /**
             * Append next chunk to the destination file.
             */
            int bytesCopied = OmniFiles.copyFileLeaveOutOpen(fis, destOutputStream);

            totalSize += bytesCopied;

            LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "Bytes copied, total: " + bytesCopied + ", " + totalSize);

            // Delete temp file
            if (!sourceFile.delete()) {
                error = "Delete temp file failed : " + sourceFile.getPath();
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, error);
                break;
            } else {
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "Removed " + sourceFile.getName());
            }
        }
        destOutputStream.flush();
        destOutputStream.close();

        // Done with this file, clean up.
        fileUploads.remove(targetFilename);

        JsonArray added = new JsonArray();
        if (error == null) {
            JsonObject fileObj = FileObj.makeObj(targetVolumeId, destFile, url);
            added.add(fileObj);
            wrapper.add("added", added);
            LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File upload success: " + destFile.getPath());
        } else {
            JsonArray warning = new JsonArray();
            warning.add(error);
            wrapper.add("warning", warning);
        }

        return getInputStream(wrapper);

    } catch (IOException e) {
        logException(CmdUpload.class, e);
        clearChunkFiles();
    }
    return null;
}

From source file:org.trpr.platform.batch.impl.spring.admin.SimpleJobConfigurationService.java

/**
 * Creates a temporary file, which is a duplicate of the current config file,
 * with the name {@link SimpleJobConfigurationService#SPRING_BATCH_PREV}
 * @param jobName//  w w  w.j  a v a 2  s  . c  o m
 */
private void createPrevConfigFile(String jobName) {
    File configFile = new File(this.getJobConfigURI(jobName));
    File prevFile = new File(
            this.getJobStoreURI(jobName).getPath() + SimpleJobConfigurationService.SPRING_BATCH_PREV);
    if (configFile.exists()) {
        if (prevFile.exists()) {
            prevFile.delete();
        }
        configFile.renameTo(prevFile);
        try {
            configFile.createNewFile();
        } catch (IOException e) {
            LOGGER.error("IOException while clearing config File", e);
        }
        prevFile.deleteOnExit();
    }

}

From source file:org.dcm4che3.tool.unvscp.UnvSCP.java

private static void renameTo(Association as, File from, File dest) throws IOException {
    LOG.info("{}: M-RENAME {}", new Object[] { as, from, dest });
    dest.getParentFile().mkdirs();/*from w w w  .  ja  va  2 s.co  m*/
    if (!from.renameTo(dest))
        throw new IOException("Failed to rename " + from + " to " + dest);
}

From source file:nl.tranquilizedquality.itest.cargo.AbstractInstalledContainerUtil.java

/**
 * Installs the container and the application configuration. It also sets
 * some system properties so the container can startup properly. Finally it
 * sets up additional configuration like jndi.proprties files etc.
 *///w ww.j  a v  a  2 s . co  m
protected void setupContainer() {
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Cleaning up " + containerName + "...");
    }

    // In windows the renaming causes problem when:
    // - The zip file has not the same name of the installed directory.
    // - The ZipURLInstaller fails.
    final String operatingSystem = System.getProperty("os.name");
    if (operatingSystem != null && !operatingSystem.startsWith("Windows")) {

        try {
            new File(containerHome).mkdir();
        } catch (final Exception exceptionOnMkDir) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Failed to create the directory: " + containerHome + ". Details: "
                        + exceptionOnMkDir.getMessage(), exceptionOnMkDir);
            }
            throw new ConfigurationException("Failed to create the directory: " + containerHome + ". Details: "
                    + exceptionOnMkDir.getMessage(), exceptionOnMkDir);
        }
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Installing " + containerName + "...");
        LOGGER.info("Downloading container from: " + remoteLocation);
        LOGGER.info("Container file: " + containerFile);
    }

    /*
     * Download and configure the container.
     */
    final String installDir = StringUtils.substringBeforeLast(StringUtils.chomp(containerHome, "/"), "/");
    if (StringUtils.contains(this.remoteLocation, "http")) {

        try {
            final URL remoteLocationUrl = new URL(this.remoteLocation + containerFile);
            final ZipURLInstaller installer = new ZipURLInstaller(remoteLocationUrl, installDir, installDir);
            installer.install();
        } catch (final MalformedURLException e) {
            throw new DeployException("Failed to download container!", e);
        }

        /*
         * Rename the install directory to the container home directory so
         * it doesn't matter what the name is of the zip file and avoid case
         * sensitive issues on Linux.
         */
        final String containerDir = StringUtils.stripEnd(containerFile, ".zip");
        final File installedDir = new File(installDir + "/" + containerDir + "/");
        final File destenationDir = new File(containerHome);

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Renaming: " + installedDir.getPath());
            LOGGER.info("To: " + destenationDir.getPath());
        }

        final boolean renamed = installedDir.renameTo(destenationDir);

        if (!renamed) {
            final String msg = "Failed to rename container install directory to home directory name!";
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(msg);
            }

            throw new ConfigurationException(msg);
        }

    } else {

        final Unzip unzipper = new Unzip();
        unzipper.setSrc(new File(this.remoteLocation + containerFile));
        unzipper.setDest(new File(containerHome));
        unzipper.execute();
    }

    /*
     * Setup the system properties.
     */
    systemProperties.put("cargo.server.port", containerPort.toString());

}

From source file:biz.wolschon.finance.jgnucash.JGnucash.java

/**
 * @param f/*from   ww w .jav  a 2 s  . c om*/
 * @throws FileNotFoundException
 * @throws IOException
 * @throws JAXBException
 */
private void saveFile() {
    try {
        File oldfile = new File(getWritableModel().getFile().getAbsolutePath());
        oldfile.renameTo(new File(oldfile.getName()
                + (new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss.SS").format(new Date())) + ".backup"));

        getWritableModel().writeFile(getWritableModel().getFile());
        hasChanged = false;
    } catch (FileNotFoundException e) {
        File f = getWritableModel().getFile();
        if (f == null) {
            f = new File("unknown");
        }
        LOGGER.error("cannot save file '" + f.getAbsolutePath() + "' (file not found)", e);
        JOptionPane.showMessageDialog(this, "Error",
                "cannot save file '" + f.getAbsolutePath() + "' (file not found)", JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        File f = getWritableModel().getFile();
        if (f == null) {
            f = new File("unknown");
        }
        LOGGER.error("cannot save file '" + f.getAbsolutePath() + "' (io-problem)", e);
        JOptionPane.showMessageDialog(this, "Error",
                "cannot save file '" + f.getAbsolutePath() + "' (io-problem)", JOptionPane.ERROR_MESSAGE);
    } catch (JAXBException e) {
        File f = getWritableModel().getFile();
        if (f == null) {
            f = new File("unknown");
        }
        LOGGER.error("cannot save file '" + f.getAbsolutePath() + "' (gnucash-format-problem)", e);
        JOptionPane.showMessageDialog(this, "Error",
                "cannot save file '" + f.getAbsolutePath() + "' (gnucash-format-problem)",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.idr.servlets.UploadServlet.java

/**
 * method responsible for calling the conversion and counting the number of
 * conversions performed// w  ww. j a v a  2 s  . c o m
 * @param fileName
 * @param scaleArr can be null
 * @param byteData
 * @param conTypeStr
 * @param map
 * @param session
 * @param pageCount
 * @param reference
 * @throws Exception 
 */
private void converterThread(final String fileName, final String[] scaleArr, final byte[] byteData,
        final String conTypeStr, final HashMap<String, String> map, final HttpSession session,
        final int pageCount, final String reference) throws Exception {
    final String tempFileName = fileName;
    currentThread = new Thread(new Runnable() {

        public void run() {
            try {
                if (scaleArr != null && scaleArr.length > 0) {
                    for (int z = 0; z < scaleArr.length; z++) {
                        map.put("org.jpedal.pdf2html.scaling", scaleArr[z]);
                        con.setUserFileDirName(fileName + scaleArr[z]);
                        File userPdfFile = new File(con.getUserPdfFilePath());
                        File file = new File(
                                userPdfFile.getParent() + File.separator + fileName + scaleArr[z] + ".pdf");
                        userPdfFile.renameTo(file);
                        con.setUserPdfFilePath(file.getPath());
                        totalConversions = scaleArr.length;
                        conversionCount++;
                        con.convert(conTypeStr, map);
                    }
                } else {
                    conversionCount = 1;
                    con.convert(conTypeStr, map);
                }
                session.setAttribute("isConverting", "false");
                session.setAttribute("isZipping", "false");
                session.setAttribute("href", reference);
                conversionCount = 0; //reset the conversion counter
            } catch (Exception ex) {
                session.setAttribute("href", "<div class='errorMsg'> " + ex.getMessage() + "</div>");
            }
        }
    });

    currentThread.start();

    counterThread = new Thread() {
        @Override
        public void run() {
            while (currentThread != null && currentThread.isAlive()) {
                try {
                    int totalConvertedFiles = 0;
                    String temp = fileName;
                    if (scaleArr != null && conversionCount != 0 && conversionCount <= scaleArr.length) {
                        temp = fileName + "" + scaleArr[conversionCount - 1];
                    }
                    File conDir = new File(con.getUserOutputDirPath() + File.separator + temp);
                    if (!conDir.exists()) {
                        conDir.mkdirs();
                    }
                    String extStr = null;
                    String str = conTypeStr.toLowerCase();
                    if (str.endsWith("svg")) {
                        extStr = ".svg";
                    } else if (str.endsWith("android")) {
                        extStr = ".html";
                        String appSafeFileName = fileName;
                        char firstLetter = fileName.charAt(0);
                        if (firstLetter >= '0' && firstLetter <= '9') {
                            appSafeFileName = "_" + appSafeFileName;
                        }
                        conDir = new File(con.getUserOutputDirPath() + File.separator + appSafeFileName
                                + "/assets/html/" + temp);
                    } else {
                        extStr = ".html";
                    }
                    for (String s : conDir.list()) {
                        if (pageCount == 1) {
                            if (s.endsWith(extStr)) {
                                totalConvertedFiles++;
                            }
                        } else {
                            if (s.endsWith(extStr) && !s.contains("index")) {
                                totalConvertedFiles++;
                            }
                        }
                    }
                    if (session != null) {
                        session.setAttribute("pageReached", totalConvertedFiles);
                    }
                    counterThread.sleep(1000);
                } catch (InterruptedException ex) {

                }
            }
        }
    };
    counterThread.start();
}

From source file:com.krawler.portal.tools.FileImpl.java

public boolean move(File source, File destination) {
    if (!source.exists()) {
        return false;
    }//w  ww. j av a  2 s.  co m

    destination.delete();

    return source.renameTo(destination);
}

From source file:org.ormma.controller.OrmmaAssetController.java

/**
 * Move a file to ad directory./*from ww  w . j  av a2 s . co m*/
 * 
 * @param fn
 *            the filename
 * @param filesDir
 *            the files directory
 * @param subDir
 *            the sub directory
 * @return the path where it was stored
 */
private String moveToAdDirectory(String fn, String filesDir, String subDir) {
    File file = new File(filesDir + java.io.File.separator + fn);
    File adDir = new File(filesDir + java.io.File.separator + "ad");
    adDir.mkdir();
    File dir = new File(filesDir + java.io.File.separator + "ad" + java.io.File.separator + subDir);
    dir.mkdir();
    file.renameTo(new File(dir, file.getName()));
    return dir.getPath() + java.io.File.separator;
}