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

public static boolean renameVia(File fromFile, File toFile, String viaPrefix) {
    File tempFile = new File(
            toFile.getParentFile().getAbsoluteFile() + File.separator + viaPrefix + toFile.getName());
    FileUtil.deleteRecursively(tempFile); // just in case!   

    if (!fromFile.renameTo(tempFile)) {
        return false;
    }//from  w  ww.  j  a  v  a 2  s  .co m

    if (!tempFile.renameTo(toFile)) {
        tempFile.renameTo(fromFile);
        return false;
    }

    return true;
}

From source file:com.viettel.dms.download.DownloadFile.java

/**
 * Download a file from a URL somewhere.  The download is atomic;
 * that is, it downloads to inta temporary file, then renames it to
 * the requested file name only if the download successfully
 * completes.//w  w  w.ja  v a 2 s  .c  o m
 * 
 * Returns TRUE if download succeeds, FALSE otherwise.
 * 
 * @param url            Source URL
 * @param output         Path to output file
 * @param tmpDir         Place to put file download in progress
 */
public static void download(String url, File output, File tmpDir) {
    InputStream is = null;
    OutputStream os = null;
    File tmp = null;
    try {
        VTLog.i("DownloadDB", "Downloading url :" + url);
        tmp = File.createTempFile("download", ".tmp", tmpDir);
        is = new URL(url).openStream();
        os = new BufferedOutputStream(new FileOutputStream(tmp));
        copyStream(is, os);
        tmp.renameTo(output);
        tmp = null;
    } catch (IOException e) {
        VTLog.e("DownloadDB", "Loi download file db " + e.toString());
        VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e));
        throw new RuntimeException(e);
    } catch (Exception e) {
        VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e));
        throw new RuntimeException(e);
    } finally {
        if (tmp != null) {
            try {
                tmp.delete();
                tmp = null;
            } catch (Exception ignore) {
                ;
            }
        }
        if (is != null) {
            try {
                is.close();
                is = null;
            } catch (Exception ignore) {
                ;
            }
        }
        if (os != null) {
            try {
                os.close();
                os = null;
            } catch (Exception ignore) {
                ;
            }
        }
    }
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

/**
 * @param zipFile/* w w  w .j ava 2  s. com*/
 * @param files
 * @throws java.io.IOException
 */
public static void addFilesToZip(File zipFile, Map<String, File> files) throws IOException {
    // get a temp file
    File tempFile = File.createTempFile(zipFile.getName(), null);
    // delete it, otherwise you cannot rename your existing zip to it.
    FileUtils.deleteQuietly(tempFile);

    boolean renameOk = zipFile.renameTo(tempFile);
    if (!renameOk) {
        throw new RuntimeException(
                "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
    }

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (Map.Entry<String, File> e : files.entrySet()) {
            if (e.getKey().equals(name)) {
                notInFiles = false;
                break;
            }
        }
        if (notInFiles) {
            out.putNextEntry(new ZipEntry(name));
            IOUtils.copy(zin, out);
        }
        entry = zin.getNextEntry();
    }
    // Close the streams
    zin.close();
    // Compress the files
    for (Map.Entry<String, File> e : files.entrySet()) {
        InputStream in = new FileInputStream(e.getValue());
        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(e.getKey()));
        // Transfer bytes from the file to the ZIP file

        IOUtils.copy(in, out);
        // Complete the entry
        out.closeEntry();
        IOUtils.closeQuietly(in);
    }
    // Complete the ZIP file
    IOUtils.closeQuietly(out);
    FileUtils.deleteQuietly(tempFile);
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

/**
 * @param zipFile/* ww w  .  j ava  2s  . com*/
 * @param files
 * @throws java.io.IOException
 */
public static void addStreamsToZip(File zipFile, Map<String, InputStream> files) throws IOException {
    // get a temp file
    File tempFile = File.createTempFile(zipFile.getName(), null);
    // delete it, otherwise you cannot rename your existing zip to it.
    FileUtils.deleteQuietly(tempFile);

    boolean renameOk = zipFile.renameTo(tempFile);
    if (!renameOk) {
        throw new RuntimeException(
                "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
    }

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (Map.Entry<String, InputStream> e : files.entrySet()) {
            if (e.getKey().equals(name)) {
                notInFiles = false;
                break;
            }
        }
        if (notInFiles) {
            out.putNextEntry(new ZipEntry(name));
            IOUtils.copy(zin, out);
        }
        entry = zin.getNextEntry();
    }
    // Close the streams
    zin.close();
    // Compress the files
    for (Map.Entry<String, InputStream> e : files.entrySet()) {
        InputStream in = e.getValue();
        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(e.getKey()));
        // Transfer bytes from the file to the ZIP file

        IOUtils.copy(in, out);
        // Complete the entry
        out.closeEntry();
        IOUtils.closeQuietly(in);
    }
    // Complete the ZIP file
    IOUtils.closeQuietly(out);
    FileUtils.deleteQuietly(tempFile);
}

From source file:com.github.cat.yum.store.util.YumUtil.java

private static void yumXmlSave(Document doc, RepoModule repo) throws IOException, NoSuchAlgorithmException {
    File outfile = getXmlFile(repo);
    xmlToFile(doc, outfile);/*ww w. ja  va  2s.c om*/

    String xmlCode = HashFile.getsum(outfile, ALGORITHM);
    repo.setXmlCode(xmlCode);
    repo.setXmlSize(outfile.length());
    GZipUtils.compress(outfile);

    outfile = getXmlGzFile(repo);
    String xmlGzode = HashFile.getsum(outfile, ALGORITHM);
    repo.setXmlGzCode(xmlGzode);
    repo.setXmlGzSize(outfile.length());

    outfile.renameTo(getXmlGzFile(repo, xmlGzode));
}

From source file:graphene.util.fs.FileUtils.java

/**
     * Utility method that moves a file from its current location to the new
     * target location. If rename fails (for example if the target is another
     * disk) a copy/delete will be performed instead. This is not a rename, use
     * {@link #renameFile(File, File)} instead.
     * /*from w  w w. j a va  2s .c o  m*/
     * @param toMove
     *            The File object to move.
     * @param target
     *            Target file to move to.
     * @throws IOException
     */
    public static void moveFile(final File toMove, final File target) throws IOException {
        if (!toMove.exists()) {
            throw new NotFoundException("Source file[" + toMove.getName() + "] not found");
        }
        if (target.exists()) {
            throw new NotFoundException("Target file[" + target.getName() + "] already exists");
        }

        if (toMove.renameTo(target)) {
            return;
        }

        if (toMove.isDirectory()) {
            target.mkdirs();
            copyRecursively(toMove, target);
            deleteRecursively(toMove);
        } else {
            copyFile(toMove, target);
            deleteFile(toMove);
        }
    }

From source file:maspack.fileutil.SafeFileUtils.java

/**
 * Moves a file./* w w w  .  j av  a2  s  .  c  om*/
 * <p>
 * When the destination file is on another file system, do a
 * "copy and delete".
 * 
 * @param srcDir
 * the file to be moved
 * @param destDir
 * the destination file
 * @throws NullPointerException
 * if source or destination is {@code null}
 * @throws IOException
 * if source or destination is invalid
 * @throws IOException
 * if an IO error occurs moving the file
 * @since 1.4
 */
public static void moveDirectory(File srcDir, File destDir, int options) throws IOException {

    if (srcDir == null) {
        throw new NullPointerException("Source must not be null");
    }
    if (destDir == null) {
        throw new NullPointerException("Destination must not be null");
    }
    if (!srcDir.exists()) {
        throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
    }

    boolean rename = srcDir.renameTo(destDir);
    if (!rename) {
        copyDirectory(srcDir, destDir, options);
        if (!srcDir.delete()) {
            throw new IOException(
                    "Failed to delete original file '" + srcDir + "' after copy to '" + destDir + "'");
        }
    }
}

From source file:Main.java

public static void writeContentToFile(String fileName, String contents) throws IOException {
    Log.d("writeContentToFile", fileName);
    File f = new File(fileName);
    f.getParentFile().mkdirs();//from   w  w  w  . j a va2 s.co  m
    File tempFile = new File(fileName + ".tmp");
    FileWriter fw = new FileWriter(tempFile);
    BufferedWriter bw = new BufferedWriter(fw);
    int length = contents.length();
    if (length > 0) {
        bw.write(contents);
        //         int apart =  Math.min(length, 65536);
        //         int times = length / apart;
        //         for (int i = 0; i < times; i++) {
        //            bw.write(contents, i * apart, apart);
        //         }
        //         if (length % apart != 0) {
        //            bw.write(contents, times * apart, length - times * apart);
        //         }
        bw.flush();
        fw.flush();
        bw.close();
        fw.close();
        f.delete();
        tempFile.renameTo(f);
    }
}

From source file:com.hp.test.framework.Reporting.Utlis.java

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

    try {//w ww.  j av a  2  s  .  com

        if (OriginalFile.exists()) {
            if (RenameFile.exists()) {
                RenameFile.delete();
                log.info("Already file exists with this name--so deleted");
            }
            log.info("" + RenameFile.getAbsolutePath());
            if (OriginalFile.renameTo(RenameFile)) {
                log.info("Rename succesful");
            } else {
                log.info("Rename failed");
            }
        }
    } catch (Exception e) {
        log.error("rename file failed" + e.getMessage());
    }
}

From source file:com.photon.phresco.framework.win8.util.Win8MetroCofigFileParser.java

private static File replacePath(String string, File dir, ApplicationInfo info) {
    File newFile = new File("");
    File oldFile = new File("");
    if (string.contains(HELLOWORLD) || string.startsWith(HELLOWORLD) || string.startsWith(info.getName())
            || string.contains(info.getName())) {
        oldFile = new File(dir + File.separator + string);
        String substring = info.getName();
        if (string.contains(HELLOWORLD)) {
            substring = string.substring(0, 10).replace(HELLOWORLD, info.getName());
            String substring2 = string.substring(10, string.length());
            newFile = new File(dir + File.separator + substring.concat(substring2));
        } else {// ww  w.  j a v  a2  s  . co m
            newFile = new File(dir + File.separator + substring);
        }
        oldFile.renameTo(newFile);
    }
    return newFile;
}