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.ieasy.basic.util.file.FileUtils.java

/**
 * ??/* w  w  w .ja v a2  s.com*/
 * 
 * @param filePath
 *            ??
 * @param definedName
 *            ??
 * @return
 */
public static boolean rename(String filePath, String definedName) {
    File file = new File(filePath);
    if (file.exists()) {
        String fileExt = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();

        String rename = file.getParent() + "/" + definedName + "." + fileExt;

        if (file.renameTo(new File(rename))) {
            logger.debug("???{} TO {}", file.getAbsoluteFile(), rename);
            return true;
        } else {
            logger.debug("??{} TO {}", file.getAbsoluteFile(),
                    rename);
            return false;
        }
    } else {
        logger.debug("?{}", file.getAbsoluteFile());
        return false;
    }
}

From source file:com.commsen.liferay.BuildService.java

public static void moveFile(File srcFile, File destFile) throws IOException {
    if (srcFile == null) {
        throw new NullPointerException("Source must not be null");
    }//from ww w  .ja v a2  s . com
    if (destFile == null) {
        throw new NullPointerException("Destination must not be null");
    }
    if (!srcFile.exists()) {
        throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
    }
    if (srcFile.isDirectory()) {
        throw new IOException("Source '" + srcFile + "' is a directory");
    }
    if (destFile.exists()) {
        throw new IOException("Destination '" + destFile + "' already exists");
    }
    if (destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' is a directory");
    }
    boolean rename = srcFile.renameTo(destFile);
    if (!rename) {
        FileUtils.copyFile(srcFile, destFile);
        if (!srcFile.delete()) {
            deleteQuietly(destFile);
            throw new IOException(
                    "Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'");
        }
    }
}

From source file:gobblin.util.HadoopUtils.java

/**
 * Renames a src {@link Path} on fs {@link FileSystem} to a dst {@link Path}. If fs is a {@link LocalFileSystem} and
 * src is a directory then {@link File#renameTo} is called directly to avoid a directory rename race condition where
 * {@link org.apache.hadoop.fs.RawLocalFileSystem#rename} copies the conflicting src directory into dst resulting in
 * an extra nested level, such as /root/a/b/c/e/e where e is repeated.
 *
 * @param fs the {@link FileSystem} where the src {@link Path} exists
 * @param src the source {@link Path} which will be renamed
 * @param dst the {@link Path} to rename to
 * @return true if rename succeeded, false if rename failed.
 * @throws IOException if rename failed for reasons other than target exists.
 *//*  www  .  ja v a2s  .com*/
public static boolean renamePathHandleLocalFSRace(FileSystem fs, Path src, Path dst) throws IOException {
    if (DecoratorUtils.resolveUnderlyingObject(fs) instanceof LocalFileSystem && fs.isDirectory(src)) {
        LocalFileSystem localFs = (LocalFileSystem) DecoratorUtils.resolveUnderlyingObject(fs);
        File srcFile = localFs.pathToFile(src);
        File dstFile = localFs.pathToFile(dst);

        return srcFile.renameTo(dstFile);
    } else {
        return fs.rename(src, dst);
    }
}

From source file:nl.mpcjanssen.simpletask.util.Util.java

public static void renameFile(File origFile, File newFile, boolean overwrite) {
    if (!origFile.exists()) {
        Log.e(TAG, "Error renaming file: " + origFile + " does not exist");
        throw new TodoException("Error renaming file: " + origFile + " does not exist");
    }//from w  w  w. j a va2 s  .  c o m

    createParentDirectory(newFile);

    if (overwrite && newFile.exists()) {
        if (!newFile.delete()) {
            Log.e(TAG, "Error renaming file: failed to delete " + newFile);
            throw new TodoException("Error renaming file: failed to delete " + newFile);
        }
    }

    if (!origFile.renameTo(newFile)) {
        Log.e(TAG, "Error renaming " + origFile + " to " + newFile);
        throw new TodoException("Error renaming " + origFile + " to " + newFile);
    }
}

From source file:net.librec.util.FileUtil.java

public static void renameFile(File file, String regex, String replacement) {
    String filename = file.getName();
    filename = filename.replaceAll(regex, replacement);

    String path = makeDirPath(file.getPath());
    file.renameTo(new File(path + filename));
}

From source file:com.hichinaschool.flashcards.anki.servicelayer.NoteService.java

/**
 * Considering the field is new, if it has media handle it
 * /*from   www .  j ava  2  s.  c  om*/
 * @param field
 */
private static void importMediaToDirectory(IField field) {
    String tmpMediaPath = null;
    switch (field.getType()) {
    case AUDIO:
        tmpMediaPath = field.getAudioPath();
        break;

    case IMAGE:
        tmpMediaPath = field.getImagePath();
        break;

    case TEXT:
    default:
        break;
    }
    if (tmpMediaPath != null) {
        try {
            File inFile = new File(tmpMediaPath);
            if (inFile.exists()) {
                Collection col = AnkiDroidApp.getCol();
                String mediaDir = col.getMedia().getDir() + "/";

                File mediaDirFile = new File(mediaDir);

                File parent = inFile.getParentFile();

                // If already there.
                if (mediaDirFile.getAbsolutePath().contentEquals(parent.getAbsolutePath())) {
                    return;
                }

                File outFile = new File(mediaDir + inFile.getName());

                if (!outFile.exists()) {
                    if (field.hasTemporaryMedia()) {
                        // Move
                        inFile.renameTo(outFile);
                    } else {
                        // Copy
                        InputStream in = new FileInputStream(tmpMediaPath);
                        OutputStream out = new FileOutputStream(outFile.getAbsolutePath());

                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = in.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                        in.close();
                        out.close();
                    }

                    switch (field.getType()) {
                    case AUDIO:
                        field.setAudioPath(outFile.getAbsolutePath());
                        break;

                    case IMAGE:
                        field.setImagePath(outFile.getAbsolutePath());
                        break;
                    default:
                        break;
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.todotxt.todotxttouch.util.Util.java

public static void renameFile(File origFile, File newFile, boolean overwrite) {
    if (!origFile.exists()) {
        Log.e(TAG, "Error renaming file: " + origFile + " does not exist");

        throw new TodoException("Error renaming file: " + origFile + " does not exist");
    }/*from  w w w . j  a  v  a 2 s .c  o m*/

    createParentDirectory(newFile);

    if (overwrite && newFile.exists()) {
        if (!newFile.delete()) {
            Log.e(TAG, "Error renaming file: failed to delete " + newFile);

            throw new TodoException("Error renaming file: failed to delete " + newFile);
        }
    }

    if (!origFile.renameTo(newFile)) {
        Log.e(TAG, "Error renaming " + origFile + " to " + newFile);

        throw new TodoException("Error renaming " + origFile + " to " + newFile);
    }
}

From source file:io.github.bonigarcia.wdm.Downloader.java

private static File checkPhantom(File archive, String export) throws IOException {
    File target = null;//from   www.  j  ava2 s  .  c o  m
    String phantomName = "phantomjs";
    if (export.contains(phantomName)) {
        String fileNoExtension = archive.getName().replace(".tar.bz2", "").replace(".zip", "");

        File phantomjs = null;
        try {
            phantomjs = new File(archive.getParentFile().getAbsolutePath() + File.separator + fileNoExtension
                    + File.separator + "bin" + File.separator).listFiles()[0];
        } catch (Exception e) {
            String extension = IS_OS_WINDOWS ? ".exe" : "";
            phantomjs = new File(archive.getParentFile().getAbsolutePath() + File.separator + fileNoExtension
                    + File.separator + phantomName + extension);
        }

        target = new File(archive.getParentFile().getAbsolutePath() + File.separator + phantomjs.getName());
        phantomjs.renameTo(target);

        File delete = new File(archive.getParentFile().getAbsolutePath() + File.separator + fileNoExtension);
        log.trace("Folder to be deleted: {}", delete);
        FileUtils.deleteDirectory(delete);
    } else {
        File[] ls = archive.getParentFile().listFiles();
        for (File f : ls) {
            if (IS_OS_WINDOWS) {
                if (f.getName().endsWith(".exe")) {
                    target = f;
                    break;
                }
            } else if (f.canExecute()) {
                target = f;
                break;
            }
        }
    }
    return target;
}

From source file:dk.netarkivet.harvester.harvesting.HarvestDocumentation.java

/**
 * Iterates over the (W)ARC files in the given dir and moves away files
 * that do not belong to the given job into a "lost-files" directory under oldjobs 
 * named with a timestamp./*from   w  ww .  j  ava 2  s.  co  m*/
 *
 * @param archiveProfile archive profile including filters, patterns, etc.
 * @param dir A directory containing one or more (W)ARC files.
 * @param files Information about the files produced by heritrix (jobId and harvestnamePrefix)
 */
private static void moveAwayForeignFiles(ArchiveProfile archiveProfile, File dir, IngestableFiles files) {
    File[] archiveFiles = dir.listFiles(archiveProfile.filename_filter);
    File oldJobsDir = new File(Settings.get(HarvesterSettings.HARVEST_CONTROLLER_OLDJOBSDIR));
    File lostfilesDir = new File(oldJobsDir, "lost-files-" + new Date().getTime());
    List<File> movedFiles = new ArrayList<File>();
    log.info("Looking for files not having harvestprefix '" + files.getHarvestnamePrefix() + "'");
    for (File archiveFile : archiveFiles) {
        if (!(archiveFile.getName().startsWith(files.getHarvestnamePrefix()))) {
            // move unidentified file to lostfiles directory
            log.info("removing unidentified file " + archiveFile.getAbsolutePath());
            try {
                if (!lostfilesDir.exists()) {
                    FileUtils.createDir(lostfilesDir);
                }
                File moveTo = new File(lostfilesDir, archiveFile.getName());
                archiveFile.renameTo(moveTo);
                movedFiles.add(moveTo);
            } catch (PermissionDenied e) {
                log.warn("Not allowed to make oldjobs dir '" + lostfilesDir.getAbsolutePath() + "'", e);
            }

        }
    }
    if (!movedFiles.isEmpty()) {
        log.warn("Found files not belonging to job " + files.getJobId()
                + ", the following files have been stored for later: " + movedFiles);
    }
}

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

private static void changeHellworld(ApplicationInfo info) throws PhrescoException {
    BufferedReader br = null;/*from  w w  w  .j ava 2s  .  c o m*/
    BufferedWriter bw = null;
    File path = new File(getProjectHome(info) + File.separator + Constants.SOURCE_DIR + File.separator
            + HELLOWORD_SOLUTIONFILE);
    File tempFile = new File(
            getProjectHome(info) + File.separator + Constants.SOURCE_DIR + File.separator + TEMP_FOLDER);
    File newFile = new File(getProjectHome(info) + File.separator + Constants.SOURCE_DIR + File.separator
            + HELLOWORD_SOLUTIONFILE);
    try {
        br = new BufferedReader(new FileReader(path));
        bw = new BufferedWriter(new FileWriter(tempFile));
        String line;
        while ((line = br.readLine()) != null) {
            if (line.contains(HELLOWORLD)) {
                line = line.replace(HELLOWORLD, info.getName());
            }
            bw.write(line + NEWLINE);
        }
    } catch (Exception e) {
        return;
    } finally {
        Utility.closeReader(br);
        Utility.closeWriter(bw);
    }
    FileUtil.delete(path);
    tempFile.renameTo(newFile);
}