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:Main.java

public static void saveISToFile(InputStream is, String fileName) throws IOException {
    File file = new File(fileName);
    file.getParentFile().mkdirs();/* w w  w. j  av a  2s  .  co  m*/
    File tempFile = new File(fileName + ".tmp");
    FileOutputStream fos = new FileOutputStream(tempFile);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    BufferedInputStream bis = new BufferedInputStream(is);
    byte[] barr = new byte[32768];
    int read = 0;
    while ((read = bis.read(barr)) > 0) {
        bos.write(barr, 0, read);
    }
    bis.close();
    bos.flush();
    fos.flush();
    bos.close();
    fos.close();
    file.delete();
    tempFile.renameTo(file);
}

From source file:com.alibaba.rocketmq.common.MixAll.java

/**
 * /*from   ww  w. ja va  2s. c  o  m*/
 */
public static final void string2File(final String str, final String fileName) throws IOException {
    // 
    String tmpFile = fileName + ".tmp";
    string2FileNotSafe(str, tmpFile);

    // ?
    String bakFile = fileName + ".bak";
    String prevContent = file2String(fileName);
    if (prevContent != null) {
        string2FileNotSafe(prevContent, bakFile);
    }

    // ?
    File file = new File(fileName);
    file.delete();

    // ?
    file = new File(tmpFile);
    file.renameTo(new File(fileName));
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static void forceUpdate() throws IOException, VcdiffDecodeException {
    File backupFile = new File(DATA_DIR, "helios.jar.bak");
    try {// ww w  . jav a  2  s . co  m
        Files.copy(IMPL_FILE.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException exception) {
        // We're going to wrap it so end users know what went wrong
        throw new IOException(String.format("Could not back up Helios implementation (%s %s, %s %s)",
                IMPL_FILE.canRead(), IMPL_FILE.canWrite(), backupFile.canRead(), backupFile.canWrite()),
                exception);
    }
    URL latestVersion = new URL("https://ci.samczsun.com/job/Helios/lastStableBuild/buildNumber");
    HttpURLConnection connection = (HttpURLConnection) latestVersion.openConnection();
    if (connection.getResponseCode() == 200) {
        boolean aborted = false;

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        copy(connection.getInputStream(), outputStream);
        String version = new String(outputStream.toByteArray(), "UTF-8");
        System.out.println("Latest version: " + version);
        int intVersion = Integer.parseInt(version);

        loop: while (true) {
            int buildNumber = loadHelios().buildNumber;
            int oldBuildNumber = buildNumber;
            System.out.println("Current Helios version is " + buildNumber);

            if (buildNumber < intVersion) {
                while (buildNumber <= intVersion) {
                    buildNumber++;
                    URL status = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber + "/api/json");
                    HttpURLConnection con = (HttpURLConnection) status.openConnection();
                    if (con.getResponseCode() == 200) {
                        JsonObject object = Json.parse(new InputStreamReader(con.getInputStream())).asObject();
                        if (object.get("result").asString().equals("SUCCESS")) {
                            JsonArray artifacts = object.get("artifacts").asArray();
                            for (JsonValue value : artifacts.values()) {
                                JsonObject artifact = value.asObject();
                                String name = artifact.get("fileName").asString();
                                if (name.contains("helios-") && !name.contains(IMPLEMENTATION_VERSION)) {
                                    JOptionPane.showMessageDialog(null,
                                            "Bootstrapper is out of date. Patching cannot continue");
                                    aborted = true;
                                    break loop;
                                }
                            }
                            URL url = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber
                                    + "/artifact/target/delta.patch");
                            con = (HttpURLConnection) url.openConnection();
                            if (con.getResponseCode() == 200) {
                                File dest = new File(DATA_DIR, "delta.patch");
                                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                copy(con.getInputStream(), byteArrayOutputStream);
                                FileOutputStream fileOutputStream = new FileOutputStream(dest);
                                fileOutputStream.write(byteArrayOutputStream.toByteArray());
                                fileOutputStream.close();
                                File cur = IMPL_FILE;
                                File old = new File(IMPL_FILE.getAbsolutePath() + "." + oldBuildNumber);
                                if (cur.renameTo(old)) {
                                    VcdiffDecoder.decode(old, dest, cur);
                                    old.delete();
                                    dest.delete();
                                    continue loop;
                                } else {
                                    throw new IllegalArgumentException("Could not rename");
                                }
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(null,
                                "Server returned response code " + con.getResponseCode() + " "
                                        + con.getResponseMessage() + "\nAborting patch process",
                                null, JOptionPane.INFORMATION_MESSAGE);
                        aborted = true;
                        break loop;
                    }
                }
            } else {
                break;
            }
        }

        if (!aborted) {
            int buildNumber = loadHelios().buildNumber;
            System.out.println("Running Helios version " + buildNumber);
            JOptionPane.showMessageDialog(null, "Updated Helios to version " + buildNumber + "!");
            Runtime.getRuntime().exec(new String[] { "java", "-jar", BOOTSTRAPPER_FILE.getAbsolutePath() });
        } else {
            try {
                Files.copy(backupFile.toPath(), IMPL_FILE.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException exception) {
                // We're going to wrap it so end users know what went wrong
                throw new IOException("Critical Error! Could not restore Helios implementation to original copy"
                        + "Try relaunching the Bootstrapper. If that doesn't work open a GitHub issue with details",
                        exception);
            }
        }
        System.exit(0);
    } else {
        throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
    }
}

From source file:net.sourceforge.fullsync.cli.Main.java

private static void backupFile(final File old, final File current, final String backupName) throws IOException {
    try (FileInputStream fis = new FileInputStream(old); FileOutputStream fos = new FileOutputStream(current)) {
        try (FileChannel in = fis.getChannel(); FileChannel out = fos.getChannel()) {
            in.transferTo(0, in.size(), out);
        }/* w w w .j  a  va  2 s. co m*/
        old.renameTo(new File(backupName));
    }
}

From source file:com.aurel.track.lucene.util.FileUtil.java

public static boolean move(File source, File destination) {
    if (!source.exists()) {
        return false;
    }/*from   w  w  w. j av  a 2 s  .  c  o  m*/

    destination.delete();

    return source.renameTo(destination);
}

From source file:com.microsoft.tfs.core.util.internal.AppleSingleUtil.java

private static void renameFile(final File source, final File target) throws IOException {
    if (target.delete() == false) {
        final String message = MessageFormat.format(
                Messages.getString("AppleSingleUtil.ErrorDeletingFileForReplacementFormat"), //$NON-NLS-1$
                target.getAbsolutePath());

        log.error(message);// w  w w .j av a  2s  .c o m
        throw new IOException(message);
    }

    if (source.renameTo(target) == false) {
        final String message = MessageFormat.format(
                Messages.getString("AppleSingleUtil.ErrorRenamingTempFileFormat"), //$NON-NLS-1$
                source.getAbsolutePath(), target.getAbsolutePath());

        log.error(message);
        throw new IOException(message);
    }
}

From source file:com.blazemeter.bamboo.plugin.ServiceManager.java

public static void downloadJtlReport(Api api, String sessionId, File jtlDir, BuildLogger logger) {

    String dataUrl = null;/*from w  ww.  j a va2  s.com*/
    URL url = null;
    try {
        JSONObject jo = api.retrieveJtlZip(sessionId);
        JSONArray data = jo.getJSONObject(JsonConstants.RESULT).getJSONArray(JsonConstants.DATA);
        for (int i = 0; i < data.length(); i++) {
            String title = data.getJSONObject(i).getString("title");
            if (title.equals("Zip")) {
                dataUrl = data.getJSONObject(i).getString(JsonConstants.DATA_URL);
                break;
            }
        }
        File jtlZip = new File(jtlDir + "/" + sessionId + "-" + Constants.BM_ARTEFACTS);
        url = new URL(dataUrl);
        logger.addBuildLogEntry("Jtl url = " + url.toString() + " sessionId = " + sessionId);
        int i = 1;
        boolean jtl = false;
        while (!jtl && i < 4) {
            try {
                logger.addBuildLogEntry("Downloading JTLZIP for sessionId = " + sessionId + " attemp # " + i);
                int conTo = (int) (10000 * Math.pow(3, i - 1));
                logger.addBuildLogEntry("Saving ZIP to " + jtlZip.getAbsolutePath());
                FileUtils.copyURLToFile(url, jtlZip, conTo, 30000);
                jtl = true;
            } catch (Exception e) {
                logger.addErrorLogEntry("Unable to get JTLZIP from " + url + ", " + e);
            } finally {
                i++;
            }
        }
        String jtlZipCanonicalPath = jtlZip.getCanonicalPath();
        unzip(jtlZip.getAbsolutePath(), jtlZipCanonicalPath.substring(0, jtlZipCanonicalPath.length() - 4),
                logger);
        File sample_jtl = new File(jtlDir, "sample.jtl");
        File bm_kpis_jtl = new File(jtlDir, Constants.BM_KPIS);
        if (sample_jtl.exists()) {
            sample_jtl.renameTo(bm_kpis_jtl);
        }
        FileUtils.deleteQuietly(jtlZip);
    } catch (JSONException e) {
        logger.addErrorLogEntry("Unable to get  JTLZIP from " + url + " " + e.getMessage());
    } catch (MalformedURLException e) {
        logger.addErrorLogEntry("Unable to get  JTLZIP from " + url + " " + e.getMessage());
    } catch (IOException e) {
        logger.addErrorLogEntry("Unable to get JTLZIP from " + url + " " + e.getMessage());
    } catch (Exception e) {
        logger.addErrorLogEntry("Unable to get JTLZIP from " + url + " " + e.getMessage());
    }
}

From source file:Main.java

/**
 *
 * @param fi/*from  w ww.  j  a  va 2 s  .  c  o  m*/
 * @param newName
 * @return
 */
public static File renameTo(File fi, String newName) {
    /* File.renameTo is a abstract file rename finction .
     * I override this function which return File but boolean.
     * To get the new File obj , you can separately rename the file you want to .
     * Example code:
     *
    File f = new File("D:\\abc.def") ;
    File tmp = renameTo(f,"a.a") ;
    renameTo(tmp,"b.b") ;
     */
    //It can rename the File to the same dir.
    String dest = fi.getParent();
    dest += "\\" + newName;
    //System.out.println("Rename To : "+dest) ;
    File newNameFile = new File(dest);
    fi.renameTo(newNameFile);
    return newNameFile;
}

From source file:com.symbian.driver.core.processors.EmulatorPreProcessor.java

/**
 * @param lFile/*  www  .j  a  va  2s  .  c  o m*/
 * @return The backed up file.
 * @throws IOException
 */
public static final File backupFile(File lFile) throws IOException {
    if (lFile.isFile()) {

        LOGGER.info("Backup file: " + lFile);
        File lFileBackup = new File(lFile.getCanonicalPath() + BACKUP);

        if (!lFile.renameTo(lFileBackup)) {

            LOGGER.warning("Overwriting previous backup file at: " + lFileBackup + "; with: " + lFile);
            lFileBackup.delete();

            if (!lFile.renameTo(lFileBackup)) {
                throw new IOException("Could not backup old file: " + lFile);
            }
        }

        return lFileBackup;
    }

    return null;
}

From source file:controller.InputSanitizer.java

private static String checkAttachmentForFiles(String description, String uploadDir)
        throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    String modifiedDescription = "";
    if (description.contains("href=\"/uploads/")) // suche andere Files (PDF, Code... etc)
    {// w  w  w  .ja  va2 s  .c  om
        // die Schleife ist notwenidig falls mehrere Dateien hinzugeuegt werden
        // andernfalls wuerde nur die erste zu MD5 
        String[] split = description.split("<a");
        String newSourceString = "href=\"" + uploadDir;
        System.out.println("newSourceString: " + newSourceString);

        if (uploadDir.equals("webapps/uploads/")) // if real server use this
        {
            newSourceString = "href=\"/uploads/";
        }

        for (String s : split) {
            if (s.contains("href=\"/uploads/")) {
                s = s.replaceFirst("href=\"/uploads/", newSourceString);

                int indexBegin = s.indexOf(newSourceString) + newSourceString.length();
                int indexEnd = s.indexOf("\"", indexBegin + 1);

                String oldFilename = s.substring(indexBegin, indexEnd);
                String file = uploadDir + s.substring(indexBegin, indexEnd);

                MessageDigest md = MessageDigest.getInstance("MD5");
                String digest = getDigest(new FileInputStream(file), md, 2048);

                File oldFile = new File(uploadDir + s.substring(indexBegin, indexEnd));
                File md5File = new File(uploadDir + digest);
                //  Funktioniert unter windows nicht
                if (!oldFile.renameTo(md5File)) {
                    System.out.println("Renaming went wrong");
                }

                s = s.replace(oldFilename, digest);
            }

            if (s.contains("href=\"http") || s.contains("href=\"www") || s.contains(newSourceString)) // http links abfangen
            {
                s = "<a" + s;
            }

            modifiedDescription = modifiedDescription + s;
        }
    } else {
        modifiedDescription = description;
    }

    System.out.println("descr: " + modifiedDescription);
    return modifiedDescription;
}