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.liferay.util.FileUtil.java

public static boolean move(File source, File destination) {
    if (!source.exists()) {
        return false;
    }/*  w w w .jav  a2  s  .  co m*/

    destination.delete();

    boolean success = source.renameTo(destination);

    // if the rename fails, copy

    if (!success) {
        copyFile(source, destination);
        success = source.delete();
    }
    return success;
}

From source file:marytts.util.io.FileUtils.java

public static void rename(String existingFile, String newFilename) {
    if (exists(existingFile)) {
        File oldFile = new File(existingFile);
        oldFile.renameTo(new File(newFilename));
    }/*from   w w w.  ja  va  2 s. co m*/
}

From source file:net.sf.jasperreports.eclipse.util.FileUtils.java

public static File fileRenamed(File file, String strFilename, String ext, boolean showWarning)
        throws CoreException {
    String fname = strFilename + ext;
    if (fname.equals(file.getAbsolutePath()))
        return file;
    deleteFileIfExists(null, fname);//from   w ww .  j a v a  2s  .  c  om

    file.renameTo(new File(fname));
    if (showWarning)
        UIUtils.showWarning(NLS.bind(Messages.FileUtils_DifferentFileTypeWarning, fname));
    return new File(fname);
}

From source file:ai.susi.json.JsonFile.java

/**
 * write a json file in transaction style: first write a temporary file,
 * then rename the original file to another temporary file, then rename the
 * just written file to the target file name, then delete all other temporary files.
 * @param file//w  w w  . j a  va  2 s . c om
 * @param json
 * @throws IOException
 */
public static void writeJson(File file, JSONObject json) throws IOException {
    if (file == null)
        throw new IOException("file must not be null");
    if (json == null)
        throw new IOException("json must not be null");
    if (!file.exists())
        file.createNewFile();
    File tmpFile0 = new File(file.getParentFile(), file.getName() + "." + System.currentTimeMillis());
    File tmpFile1 = new File(tmpFile0.getParentFile(), tmpFile0.getName() + "1");
    FileWriter writer = new FileWriter(tmpFile0);
    writer.write(json.toString(2));
    writer.close();
    file.renameTo(tmpFile1);
    tmpFile0.renameTo(file);
    tmpFile1.delete();
}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.component.TestCaseExporter.java

private static Window getExportWindow(TreeTable summary, List<TestCaseExecutionServer> executions, int tcID) {
    VMWindow w = new VMWindow(TRANSLATOR.translate("general.export"));
    VerticalLayout vl = new VerticalLayout();
    summary.setSizeFull();/*w  ww  .  j a va  2s.  co  m*/
    vl.addComponent(summary);
    Button export = new Button(TRANSLATOR.translate("general.export"));
    List<File> attachments = new ArrayList<>();
    export.addClickListener(listener -> {
        if (ArrayUtils.contains(summary.getColumnHeaders(), TRANSLATOR.translate("general.attachment"))) {
            //Hide the attachment column as it doesn't work well on the export.
            summary.setColumnCollapsingAllowed(true);
            summary.setColumnCollapsed(TRANSLATOR.translate("general.attachment"), true);
        }
        String basePath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath() + File.separator
                + "VAADIN" + File.separator + "temp" + File.separator;
        if (executions != null) {
            //Also send the attachments
            executions.forEach(execution -> {
                execution.getExecutionStepList().forEach(es -> {
                    if (tcID < 0 || es.getExecutionStepPK().getStepTestCaseId() == tcID) {
                        es.getExecutionStepHasAttachmentList().forEach(esha -> {
                            AttachmentServer as = new AttachmentServer(esha.getAttachment().getAttachmentPK());
                            File f = null;
                            switch (esha.getAttachment().getAttachmentType().getType()) {
                            case "comment": //Create a pdf version of the comment
                                try {
                                    String fileName = basePath + TRANSLATOR.translate("general.test.case") + "-"
                                            + es.getStep().getTestCase().getName() + "-"
                                            + TRANSLATOR.translate("general.comment") + "-"
                                            + TRANSLATOR.translate("general.step") + "-"
                                            + es.getStep().getStepSequence() + ".pdf";
                                    f = Tool.convertToPDF(as.getTextValue(), fileName);
                                } catch (IOException ex) {
                                    Exceptions.printStackTrace(ex);
                                }
                                break;
                            default:
                                File temp = as.getAttachedFile(basePath);
                                f = new File(basePath + TRANSLATOR.translate("general.test.case") + "-"
                                        + es.getStep().getTestCase().getName() + "-"
                                        + TRANSLATOR.translate("general.attachment") + "-" + temp.getName());
                                temp.renameTo(temp);
                            }
                            if (f != null) {
                                attachments.add(f);
                            }
                        });
                    }
                    if (es.getExecutionStepHasIssueList() != null) {
                        es.getExecutionStepHasIssueList().forEach(eshi -> {
                            try {
                                Issue i = eshi.getIssue();
                                String fileName = basePath + TRANSLATOR.translate("general.test.case") + "-"
                                        + es.getStep().getTestCase().getName() + "-"
                                        + TRANSLATOR.translate("general.issue") + "-"
                                        + TRANSLATOR.translate("general.step") + "-"
                                        + es.getStep().getStepSequence() + ".pdf";
                                //Create a string version of the issue
                                StringBuilder sb = new StringBuilder();
                                sb.append(TRANSLATOR.translate("general.summary")).append(i.getTitle())
                                        .append('\n').append(TRANSLATOR.translate("issue.type")).append(':')
                                        .append(TRANSLATOR.translate(i.getIssueType().getTypeName()))
                                        .append('\n').append(TRANSLATOR.translate("creation.time")).append(':')
                                        .append(i.getCreationTime()).append('\n')
                                        .append(TRANSLATOR.translate("issue.detail")).append(':')
                                        .append(i.getDescription()).append('\n');
                                if (i.getIssueResolutionId() != null) {
                                    sb.append(TRANSLATOR.translate("issue.resolution")).append(':')
                                            .append(TRANSLATOR.translate(i.getIssueResolutionId().getName()))
                                            .append('\n');
                                }
                                attachments.add(Tool.convertToPDF(sb.toString(), fileName));
                            } catch (IOException ex) {
                                Exceptions.printStackTrace(ex);
                            }
                        });
                    }
                });
            });
        }
        if (!attachments.isEmpty()) {
            try {
                File attachment = Tool.createZipFile(attachments, basePath + "Attachments.zip");
                LOG.log(Level.FINE, "Downloading: {0}", attachment.getAbsolutePath());
                ((VMUI) UI.getCurrent()).sendConvertedFileToUser(UI.getCurrent(), attachment,
                        attachment.getName(), Tool.getMimeType(attachment));
            } catch (IOException ex) {
                LOG.log(Level.SEVERE, "Error downloading attachments!", ex);
            }
        }
        //Create the Excel file
        ExcelExport excelExport = new ExcelExport(summary);
        excelExport.excludeCollapsedColumns();
        excelExport.setReportTitle(TRANSLATOR.translate("general.export"));
        excelExport.setDisplayTotals(false);
        excelExport.export();
        UI.getCurrent().removeWindow(w);
    });
    vl.addComponent(export);
    summary.getItemIds().forEach(id -> {
        summary.setCollapsed(id, false);
        summary.getChildren(id).forEach(child -> {
            summary.setCollapsed(child, false);
        });
    });
    w.setContent(vl);
    w.setSizeFull();
    return w;
}

From source file:org.ala.spatial.web.services.DownloadController.java

private static void fixMaxentFiles(String pid, File dir) {
    try {/*from   w  w  w.j a v a  2  s.  c  o  m*/
        File tmpdir = new File(dir.getParent() + "/temp/" + pid);
        //FileCopyUtils.copy(new FileInputStream(dir), new FileOutputStream(tmpdir));
        FileUtils.copyDirectory(dir, tmpdir);

        //File grd = new File(tmpdir.getAbsolutePath() + "/" + pid + ".grd");
        //File grdnew = new File(tmpdir.getAbsolutePath() + "/prediction.grd");

        //File gri = new File(tmpdir.getAbsolutePath() + "/" + pid + ".gri");
        //File grinew = new File(tmpdir.getAbsolutePath() + "/prediction.gri");

        File rsp = new File(tmpdir.getAbsolutePath() + "/removedSpecies.txt");
        File rspnew = new File(tmpdir.getAbsolutePath() + "/prediction_removedSpecies.txt");

        File msp = new File(tmpdir.getAbsolutePath() + "/maskedOutSensitiveSpecies.txt");
        File mspnew = new File(tmpdir.getAbsolutePath() + "/prediction_maskedOutSensitiveSpecies.txt");

        //grd.renameTo(grdnew);
        //gri.renameTo(grinew);
        rsp.renameTo(rspnew);
        msp.renameTo(mspnew);

        (new File(tmpdir.getAbsolutePath() + "/species.zip")).delete();
        (new File(tmpdir.getAbsolutePath() + "/species.bat")).delete();
        (new File(tmpdir.getAbsolutePath() + "/" + pid + ".grd")).delete();
        (new File(tmpdir.getAbsolutePath() + "/" + pid + ".gri")).delete();

    } catch (Exception e) {
        System.out.println("Unable to fix Prediction files");
        e.printStackTrace(System.out);
    }
}

From source file:com.sustainalytics.crawlerfilter.PDFTitleGeneration.java

/**
 * This method renames the given PDF/*from  w  ww.j a  v a2  s  .  c  o m*/
 * @param file is a File object
 * @param finalTitle is a String
 */
public static void renameFile(File pdfFile, File textFile, String finalTitle) {
    String newTitle = pdfFile.getParentFile().getAbsolutePath() + "/" + finalTitle;
    File pdfFileWithTitle = new File(newTitle + ".pdf");
    File textFileWithTitle = new File(newTitle + ".txt");
    if (!pdfFileWithTitle.exists()) {
        logger.info("Renaming " + pdfFile.getName() + "-->" + pdfFileWithTitle.getName());
        logger.info("\n\n");
        pdfFile.renameTo(pdfFileWithTitle);
        textFile.renameTo(textFileWithTitle);
    } else {
        logger.info("Renaming failed. File " + pdfFileWithTitle + " already exists");
        try {
            logger.info("Deleting " + pdfFile.getName());
            FileUtils.forceDelete(pdfFile);
            FileUtils.forceDelete(textFile);
        } catch (IOException e) {
            logger.info(pdfFile.getName() + "could not be force deleted");
        }
    }
}

From source file:de.tbuchloh.kiskis.persistence.PersistenceManager.java

private static void createBackup(final TPMDocument doc) throws IOException {
    if (doc.getFile().exists()) {
        deleteOldBackups(doc.getFile());
        if (maxBackups > 0) {
            final String orig = doc.getFile().getAbsolutePath();
            final String bakExt = BAK_ID + BAK_EXT.format(new Date());
            final File bak = new File(orig + bakExt);
            LOG.debug("creating backup: " + bak.getName());

            backupAttachments(doc.getFile(), bakExt);

            final File tmp = new File(doc.getFile().getAbsolutePath());
            if (!tmp.renameTo(bak)) {
                throw new IOException(String.format("The file %1$s cannot be renamed to %2$s!", tmp, bak));
            }//from   w  w  w.  j  a v a  2  s. co m
            assert bak.exists() && !doc.getFile().exists();
        }
    }
}

From source file:com.bristle.javalib.io.FileUtil.java

/**************************************************************************
* Rename the file with the specified old name to the specified new name.
*@param  strOldFileName         Old name of the file.
*@param  strNewFileName         New name of the file.
*@throws FileRenameException    When unable to rename the file.
**************************************************************************/
public static void rename(String strOldFileName, String strNewFileName) throws FileRenameException {
    File fileOld = new File(strOldFileName);
    File fileNew = new File(strNewFileName);
    if (!fileOld.renameTo(fileNew)) {
        throw new FileRenameException("Unable to rename file " + strOldFileName + " to " + strNewFileName);
    }//from  w  ww  .j a  va2  s  .  c  o  m
}

From source file:fr.paris.lutece.plugins.rss.service.RssGeneratorService.java

/**
 * Creates the pushrss file in the directory
 *
 * @param strRssFileName The file's name that must be deleted
 * @param strRssDocument The content of the new RSS file
 *///from   w  w  w  .  j a va2  s  . c o  m
public static void createFileRss(String strRssFileName, String strRssDocument) {
    FileWriter fileRssWriter;

    try {
        // fetches the pushRss directory path
        String strFolderPath = AppPathService.getPath(RssGeneratorService.PROPERTY_RSS_STORAGE_FOLDER_PATH, "");

        // Test if the pushRss directory exist and create it if it doesn't exist
        if (!new File(strFolderPath).exists()) {
            File fileFolder = new File(strFolderPath);
            fileFolder.mkdir();
        }

        // Creates a temporary RSS file
        String strFileRss = AppPathService.getPath(RssGeneratorService.PROPERTY_RSS_STORAGE_FOLDER_PATH, "")
                + strRssFileName;
        String strFileDirectory = AppPathService.getPath(RssGeneratorService.PROPERTY_RSS_STORAGE_FOLDER_PATH,
                "");
        File fileRss = new File(strFileRss);
        File fileRssDirectory = new File(strFileDirectory);
        File fileRssTemp = File.createTempFile("tmp", null, fileRssDirectory);
        fileRssWriter = new FileWriter(fileRssTemp);
        fileRssWriter.write(strRssDocument);
        fileRssWriter.flush();
        fileRssWriter.close();

        // Deletes the file if the file exists and renames the temporary file into the file
        if (new File(strFileRss).exists()) {
            File file = new File(strFileRss);
            file.delete();
        }

        fileRssTemp.renameTo(fileRss);
    } catch (IOException e) {
        AppLogService.error(e.getMessage(), e);
    } catch (NullPointerException e) {
        AppLogService.error(e.getMessage(), e);
    }
}