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:com.mindquarry.desktop.workspace.SVNTestBase.java

/**
 * Renames an existing file or directory inside the working copy (wcPath).
 *//*w w  w .  j a  v a2 s.c  o m*/
protected void move(String from, String to) throws IOException {
    File file = new File(wcPath, from);
    File toFile = new File(wcPath, to);
    if (!file.renameTo(toFile)) {
        throw new IOException("Could not rename '" + from + "' to '" + to + "'");
    }
}

From source file:com.scooter1556.sms.server.io.AdaptiveStreamingProcess.java

private void postProcess(String path, String format) {
    // Process for transcoding
    Process postProcess = null;/*from  ww  w .  j a  v  a  2s .  c o  m*/

    LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME,
            "Post processing segment " + path + " with format '" + format + "'", null);

    try {
        // Generate post-process command
        List<String> command = new ArrayList<>();
        command.add(transcoder.getPath().toString());
        command.add("-i");
        command.add(path);
        command.add("-c:a");
        command.add("copy");
        command.add("-f");
        command.add(format);
        command.add(path + ".tmp");

        LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME,
                StringUtils.join(command, " "), null);

        ProcessBuilder processBuilder = new ProcessBuilder(command);
        postProcess = processBuilder.start();
        new NullStream(postProcess.getInputStream()).start();

        // Wait for process to finish
        postProcess.waitFor();

        // Rename file once complete
        File temp = new File(path + ".tmp");
        File segment = new File(path + "." + format);

        if (temp.exists()) {
            temp.renameTo(segment);
        }
    } catch (IOException ex) {
        LogService.getInstance().addLogEntry(Level.ERROR, CLASS_NAME, "Failed to post-process file " + path,
                ex);
    } catch (InterruptedException ex) {
        //Do nothing...
    } finally {
        if (postProcess != null) {
            postProcess.destroy();
        }
    }
}

From source file:edu.du.penrose.systems.fedoraApp.batchIngest.data.BagHandler.java

/**
 * This function OVERWRITES. We assumes the bag name was checked as unique in the work directory and has already been extracted, throwing
 * and error will be of no value./*from  www  .j a  v  a  2 s.  c o m*/
 * 
 * @throws IOException
 */
private void deleteBagDirMoveBagToCompletedDir() throws IOException {
    this.logger.info("Move bag file:" + this.myBagFileName + " to " + this.myCompletedBatchFileDir);
    FileUtil.deleteDirectoryTree(new File(this.myBagDirectoryPath));

    File moveFile = new File(this.myCompletedBatchFileDir + this.myBagFileName);

    File bagFile = new File(this.myRootDir + this.myBagFileName);

    bagFile.renameTo(moveFile);
}

From source file:com.mindquarry.desktop.workspace.SVNTestBase.java

/**
 * Renames an existing file or directory inside the 'remote' working copy (wcPathRemote).
 *//*from w w  w. j  a  va 2  s. com*/
protected void moveRemote(String from, String to) throws IOException {
    File file = new File(wcPathRemote, from);
    File toFile = new File(wcPathRemote, to);
    if (!file.renameTo(toFile)) {
        throw new IOException("Could not rename '" + from + "' to '" + to + "'");
    }
}

From source file:au.edu.uq.cmm.paul.queue.AbstractQueueFileManager.java

@Override
public final File renameGrabbedDatafile(File file) throws QueueFileException {
    String extension = FilenameUtils.getExtension(file.toString());
    if (!extension.isEmpty()) {
        extension = "." + extension;
    }//from   www.j av  a  2s . c  om
    for (int i = 0; i < RETRY; i++) {
        File newFile = generateUniqueFile(extension, false);
        if (!file.renameTo(newFile)) {
            if (!Files.exists(newFile.toPath(), LinkOption.NOFOLLOW_LINKS)) {
                throw new QueueFileException("Unable to rename file or symlink " + file + " to " + newFile);
            }
        } else {
            return newFile;
        }
    }
    throw new QueueFileException(RETRY + " attempts to rename file / symlink failed!");
}

From source file:com.remobile.file.LocalFilesystem.java

private void copyFile(Filesystem srcFs, LocalFilesystemURL srcURL, File destFile, boolean move)
        throws IOException, InvalidModificationException, NoModificationAllowedException {
    if (move) {/*from  w w  w.  java 2s .  c  om*/
        String realSrcPath = srcFs.filesystemPathForURL(srcURL);
        if (realSrcPath != null) {
            File srcFile = new File(realSrcPath);
            if (srcFile.renameTo(destFile)) {
                return;
            }
            // Trying to rename the file failed.  Possibly because we moved across file system on the device.
        }
    }

    CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(srcFs.toNativeUri(srcURL));
    copyResource(offr, new FileOutputStream(destFile));

    if (move) {
        srcFs.removeFileAtLocalURL(srcURL);
    }
}

From source file:com.naryx.tagfusion.cfm.engine.cfEngine.java

public synchronized static void writeXmlFile(xmlCFML newXmlCFML, boolean notifyListeners)
        throws cfmRunTimeException {

    if (thisInstance.bRemoteOpenBDXML) {
        log("Attempted to update a remote bluedragon.xml; operation failed");
        return;/*w ww. j  a v  a 2 s.co m*/
    }

    File xmlFileName = getXmlFileName();

    if ((xmlFileName != null) && (xmlFileName.canWrite())) {
        // delete the oldest (10th) backup; increment the numbers of the remaining backups
        for (int backupNo = 10; backupNo > 0; backupNo--) {
            File backupFile = new File(xmlFileName + ".bak." + backupNo);
            if (backupFile.exists()) {
                if (backupNo == 10) {
                    backupFile.delete();
                } else {
                    backupFile.renameTo(new File(xmlFileName + ".bak." + (backupNo + 1)));
                }
            }
        }

        // clean up older backup files
        for (int backupNo = 11; true; backupNo++) {
            File backupFile = new File(xmlFileName + ".bak." + backupNo);
            if (backupFile.exists()) {
                backupFile.delete();
            } else {
                break;
            }
        }

        // write back out the xml file to the file, saving the old one
        File xmlFile = xmlFileName;
        File newFile = new File(xmlFileName + ".bak.1");

        // Put in the last updated
        newXmlCFML.setData("server.system.lastupdated",
                com.nary.util.Date.formatDate(System.currentTimeMillis(), "dd/MMM/yyyy HH:mm.ss", Locale.US));
        newXmlCFML.setData("server.system.lastfile", newFile.toString());

        // Rename the file
        xmlFile.renameTo(newFile);

        try {
            newXmlCFML.writeTo(xmlFile);
        } catch (IOException e) {
            cfCatchData catchData = new cfCatchData();
            catchData.setMessage("failed to write configuration file, " + e.toString());
            throw new cfmRunTimeException(catchData);
        }
    } else {
        // NOTE: this will happen with BD J2EE when it is running in a WAR file,
        // or when the bluedragon.xml
        // file is marked read-only, or when something goes seriously wrong at BD
        // init time.
        cfCatchData catchData = new cfCatchData();
        catchData.setMessage("failed to write configuration file");
        throw new cfmRunTimeException(catchData);
    }

    if (notifyListeners) {
        notifyAllListenersAdmin(newXmlCFML);
    }
}

From source file:com.haw3d.jadvalKalemat.net.NYTDownloader.java

@Override
protected void download(Calendar date, String urlSuffix) throws IOException {
    login();/*from  w  w w . jav  a  2s  .c  o m*/

    URL url = new URL(this.baseUrl + urlSuffix);
    LOG.info("NYT: Downloading " + url);

    HttpGet get = new HttpGet(url.toString());
    HttpResponse response = utils.getHttpClient().execute(get);

    int status = response.getStatusLine().getStatusCode();
    if (status != 200) {
        LOG.warning("NYT: Download failed: " + response.getStatusLine());
        throw new IOException("Download failed: status " + status);
    }

    File tempFile = new File(jadvalKalematApplication.TEMP_DIR, getFilename(date));
    FileOutputStream fos = new FileOutputStream(tempFile);
    try {
        IO.copyStream(response.getEntity().getContent(), fos);
    } finally {
        fos.close();
    }

    File destFile = new File(jadvalKalematApplication.CROSSWORDS_DIR, getFilename(date));
    if (!tempFile.renameTo(destFile)) {
        throw new IOException("Failed to rename " + tempFile + " to " + destFile);
    }
}

From source file:beans.service.SharedobjectUpload.java

public String run(Map<String, String> fields, List<String> fileNames) {

    String first_name = fields.get("first_level_service_name_of_new_sharedobject");
    String second_name = fields.get("second_level_service_name_of_new_sharedobject");
    String tag_name = fields.get("new_sharedobject_tag");
    if (first_name == null || first_name.length() < 1 || second_name == null || second_name.length() < 1
            || tag_name == null || tag_name.length() < 1) {
        return ("{\"status\":100, \"message\":\"servicename and tag name should NOT be empty.\"}");

    }/*from  w ww .j ava  2  s.  com*/
    if (fileNames.size() != 1) {
        return ("{\"status\":100, \"message\":\"file field missing.\"}");

    }

    File oldFile = new File(fileNames.get(0));
    //  String baseName = oldFile.getName();
    String destName = SharedobjectTag.getSharedobjectName(first_name, second_name, tag_name, "so");//c++?
    File newFile = new File(destName);
    if (newFile.exists()) {
        return String.format("{\"status\":100, \"message\":\"file %s exists\"}", newFile.getName());

    }
    if (!oldFile.renameTo(newFile)) {
        return ("{\"status\":100, \"message\":\"rename file failed.\"}");

    }
    //
    String memo = fields.get("new_sharedobject_memo");
    if (memo == null) {
        memo = "";
    }
    String result = insertTable(first_name, second_name, tag_name, memo);
    if (result.equals("success")) {
        return String.format("{\"status\":0, \"message\":\"success\", \"file_name\":\"%s\"}",
                newFile.getName());
    } else {
        return String.format("{\"status\":100, \"message\":\"%s\"}", result);
    }

}

From source file:org.ednovo.gooru.converter.service.ConversionServiceImpl.java

@Override
public void convertDocumentToPdf(Conversion conversion) {
    JSONObject data;/*from w  ww  .j  a  v  a 2s. c  om*/
    try {
        data = new JSONObject(new JSONSerializer().serialize(conversion));
        data.put("eventName", "convert.docToPdf");

        try {
            if (conversion != null) {
                OfficeManager officeManager = new DefaultOfficeManagerConfiguration().buildOfficeManager();
                officeManager.start();

                OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
                converter.convert(new File(conversion.getSourceFilePath()),
                        new File(conversion.getTargetFolderPath() + "/" + conversion.getFileName()));
                data.put("status", "completed");
                convertPdfToImage(conversion.getTargetFolderPath() + "/" + conversion.getFileName(),
                        conversion.getResourceGooruOid(), conversion.getAuthXml());
                File file = new File(conversion.getSourceFilePath());
                file.renameTo(new File(conversion.getTargetFolderPath() + "/"
                        + StringUtils.substringBeforeLast(conversion.getFileName(), ".") + ".ppt"));
                officeManager.stop();
            }
        } catch (Exception e) {
            data.put("status", "failed");
        }
        new ClientResource(conversion.getApiEndPoint() + "v2/job/" + conversion.getJobUid() + "?sessionToken="
                + conversion.getSessionToken()).put(data.toString());
    } catch (JSONException jsonException) {
        logger.error("Failed to parse json : " + jsonException);
    }
}