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.hp.test.framework.Utlis.java

public static void renameOriginalFile(File OriginalFile, File RenameFile) {

    if (OriginalFile.exists()) {
        if (RenameFile.exists()) {
            RenameFile.delete();/*from  w w w.java  2 s.  co m*/
            log.info("Already file exists with this name--so deleted");
        }
        if (OriginalFile.renameTo(RenameFile)) {
            log.info("Rename succesful");
        } else {
            log.info("Rename failed");
        }
    }
}

From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java

public static boolean renameFile(String oldName, String newName, boolean replaceExistingFile)
        throws IOException {
    File oldFile = new File(oldName);
    File newFile = new File(newName);
    if (newFile.exists() && replaceExistingFile == false) {
        throw new IOException("The target file has already existed!");
    }/*from  w  w w. ja v  a  2 s . co m*/
    return oldFile.renameTo(newFile);
}

From source file:com.diversityarrays.kdxplore.KDXplore.java

static private java.util.logging.Logger establishLogger(ApplicationFolder appFolder) {
    // Establish logger
    java.util.logging.Logger logger = null;

    try {/*w  w w .  j  a  v  a2 s .  c  om*/
        File applicationFolder = appFolder.getApplicationFolder();

        logger = Shared.Log.getLogger();
        if (logger == null) {
            String kdxploreLog = appFolder.getApplicationName().toLowerCase() + ".log"; //$NON-NLS-1$
            File logFile = new File(applicationFolder, kdxploreLog);
            if (logFile.exists()) {
                File bakFile = new File(applicationFolder, kdxploreLog + ".bak"); //$NON-NLS-1$
                if (bakFile.exists()) {
                    bakFile.delete();
                }
                logFile.renameTo(bakFile);
            }
            java.util.logging.FileHandler fh = new FileHandler(kdxploreLog);
            fh.setFormatter(new SimpleFormatter());
            logger = java.util.logging.Logger.getLogger(appFolder.getApplicationName());
            logger.addHandler(fh);
            Shared.Log.setLogger(logger);

            logger.info("==== Log Started ===="); //$NON-NLS-1$
        }

        ExplorerProperties.getInstance(applicationFolder);
    } catch (IOException e1) {
        JOptionPane.showMessageDialog(null, e1.getMessage(), "Unable to initialise environment", //$NON-NLS-1$
                JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    return logger;
}

From source file:com.bluexml.tools.miscellaneous.PrepareSIDEModulesMigration.java

protected static void renameFile(final String versionInProjectName, String versionInProjectName2, File f) {
    String replace = f.getName().replace(versionInProjectName, versionInProjectName2);
    File file = new File(f.getParentFile(), replace);
    if (!f.getName().equals(replace)) {
        System.out.println("PrepareSIDEModulesMigration.reNameResources() try to rename file :" + f.getName()
                + " to " + file.getName());
        boolean renameTo = f.renameTo(file);
        System.out.println("PrepareSIDEModulesMigration.reNameResources() rename :" + renameTo);
    }//w w w .  j a  v  a  2 s. com
}

From source file:net.commerce.zocalo.freechart.ChartGenerator.java

private static File writeChartAsPNG(int chartWidth, int chartHeight, JFreeChart chart, File existingPngFile)
        throws IOException {
    if (!existingPngFile.getParentFile().exists()) {
        existingPngFile.getParentFile().mkdirs();
    }//from  w w w.j a  va2 s. com
    File pngFile = new File(existingPngFile.getAbsolutePath() + ".next");
    OutputStream pngStream = new FileOutputStream(pngFile);
    ChartUtilities.writeChartAsPNG(pngStream, chart, chartWidth, chartHeight);
    pngStream.close();
    if (pngFile.renameTo(existingPngFile)) {
        return existingPngFile;
    } else {
        return pngFile;
    }
}

From source file:eu.sisob.uma.restserver.services.crawler.CrawlerTask.java

public static boolean relaunch(String user, String pass, String task_code, String code_task_folder,
        String email, StringWriter message) {
    boolean success = false;

    String results_data_folder = code_task_folder + File.separator + AuthorizationManager.results_dirname;
    File results_data_dir = new File(results_data_folder);

    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {

            if (name.endsWith(AuthorizationManager.results_dirname) && dir.isDirectory()) {
                return true;
            } else {
                return false;
            }/*from   w  ww .j  a v  a2s . c  om*/
        }
    };

    try {
        int results_dir = results_data_dir.getParentFile().list(filter).length;
        results_data_dir.renameTo(new File(results_dir + "." + results_data_dir.getName()));
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.getMessage(), ex);
    }

    if (success) {
        success = CrawlerTask.launch(user, pass, task_code, code_task_folder, email, message);
    }

    return success;
}

From source file:com.sencko.basketball.stats.advanced.FIBAJsonParser.java

private static void addToCache(String cacheName, Game game)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    logger.log(Level.FINEST, "Saving file {0} to cache", cacheName);
    File file = new File("archive.zip");
    File file1 = null;//from  ww w  .ja  v  a2  s  . c o  m
    if (file.exists()) {
        //copy to archive1, return
        file1 = new File("archive1.zip");
        if (file1.exists()) {
            if (!file1.delete()) {
                logger.log(Level.WARNING, "Unable to delete file {0}", file1.getCanonicalPath());
                return;
            }
        }
        if (!file.renameTo(file1)) {
            logger.log(Level.WARNING, "Unable to rename file {0} to {1}",
                    new Object[] { file.getCanonicalPath(), file1.getCanonicalPath() });
            // unable to move to archive1 and whole operation fails!!!
            return;
        }
    }

    try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file))) {
        out.setLevel(9);
        // name the file inside the zip  file 
        out.putNextEntry(new ZipEntry(cacheName));
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out, "UTF-8");
        JsonWriter jsonWriter = new JsonWriter(outputStreamWriter);
        jsonWriter.setIndent("  ");
        builder.create().toJson(game, Game.class, jsonWriter);
        jsonWriter.flush();

        if (file1 != null) {
            try (ZipFile zipFile = new ZipFile(file1)) {
                Enumeration<? extends ZipEntry> files = zipFile.entries();
                while (files.hasMoreElements()) {
                    ZipEntry entry = files.nextElement();
                    try (InputStream in = zipFile.getInputStream(entry)) {
                        out.putNextEntry(new ZipEntry(entry.getName()));

                        IOUtils.copy(in, out);
                    }
                }
            }
            file1.delete();

        }
    }
}

From source file:com.appunity.ant.Utils.java

protected static File getNewWorkDir(Task task, String workdir, boolean... isClean)
        throws UnsupportedOperationException {
    String timedir = task.getProject().getProperty(" work.dir.timestamp");
    if (timedir != null && "true".equals(timedir)) {
        isUserTimeWorkDir = true;/*ww w .j ava  2s.co  m*/
    }
    File dir = new File(Utils.obtainValidPath(task, workdir, "work.dir"));
    if (!dir.exists()) {
        System.out.println("make dir     :" + workdir);
        dir.mkdirs();
    } else {
        if (!dir.isDirectory()) {
            File oldfile = new File(workdir + ".bak");
            for (int i = 0; oldfile.exists(); i++) {
                oldfile = new File(workdir + "." + i + ".bak");
            }
            dir.renameTo(oldfile);
            System.out.println("make dir     :" + workdir);
            dir.mkdirs();
            System.out.println(
                    "work dir " + workdir + " is not a dir, will rename old file to " + oldfile.getName());
        }
    }
    if (!dir.canWrite()) {
        throw new UnsupportedOperationException("??: " + workdir);
    }
    if (isUserTimeWorkDir) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        File file = new File(dir, df.format(new Date()));
        while (file.exists()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
            file = new File(dir, df.format(new Date()));
        }
        file.mkdirs();
        return file;
    } else {
        if (isClean != null && isClean[0]) {
            for (File object : dir.listFiles()) {
                if (object.isDirectory()) {
                    try {
                        FileUtils.deleteDirectory(object);
                        System.out.println("delete old dir: " + object);
                    } catch (IOException ex) {
                        Logger.getLogger(InitProjectTask.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    object.delete();
                    System.out.println("delete old file: " + object);
                }
            }
        }
        currentWorkDir = dir;
        return dir;
    }
}

From source file:FileHelper.java

/**
 * Move a file from one location to another.  An attempt is made to rename
 * the file and if that fails, the file is copied and the old file deleted.
 *
 * @param from file which should be moved.
 * @param to desired destination of the file.
 * @param overwrite If false, an exception will be thrown rather than overwrite a file.
 * @throws IOException if an error occurs.
 *
 * @since ostermillerutils 1.00.00//w  w  w  .  j  a va2 s. c om
 */
public static void move(File from, File to, boolean overwrite) throws IOException {
    if (to.exists()) {
        if (overwrite) {
            if (!to.delete()) {
                throw new IOException(MessageFormat.format(labels.getString("deleteerror"),
                        (Object[]) new String[] { to.toString() }));
            }
        } else {
            throw new IOException(MessageFormat.format(labels.getString("alreadyexistserror"),
                    (Object[]) new String[] { to.toString() }));
        }
    }

    if (from.renameTo(to))
        return;

    InputStream in = null;
    OutputStream out = null;
    try {
        in = new FileInputStream(from);
        out = new FileOutputStream(to);
        copy(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
        if (!from.delete()) {
            throw new IOException(MessageFormat.format(labels.getString("deleteoriginalerror"),
                    (Object[]) new String[] { from.toString(), to.toString() }));
        }
    } finally {
        if (in != null) {
            in.close();
            in = null;
        }
        if (out != null) {
            out.flush();
            out.close();
            out = null;
        }
    }
}

From source file:com.zotoh.core.util.FileUte.java

/**
 * @param srcFile/*from  w  w  w.j av  a2  s  .  c  o m*/
 * @param destFile
 * @return
 * @throws IOException
 */
public static File moveFile(File srcFile, File destFile) throws IOException {

    tstObjArg("source-file", srcFile);
    tstObjArg("dest-file", destFile);

    if (!srcFile.exists() || !srcFile.isFile()) {
        throw new IOException("\"" + srcFile + "\" does not exist or not a valid file");
    }

    if (destFile.exists()) {
        throw new IOException("\"" + destFile + "\" already exists");
    }

    if (!srcFile.renameTo(destFile)) {
        copyFile(srcFile, destFile);
        if (!srcFile.delete()) {
            FileUte.delete(destFile);
            throw new IOException("Failed to delete original file \"" + srcFile + "\"");
        }
    }

    return destFile;
}