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:aiai.ai.station.StationTaskService.java

public StationTask save(StationTask task) {
    File taskDir = prepareTaskDir(task.taskId);
    File sequenceYaml = new File(taskDir, Consts.TASK_YAML);

    if (sequenceYaml.exists()) {
        log.debug("{} file exists. Make backup", sequenceYaml.getPath());
        File yamlFileBak = new File(taskDir, Consts.TASK_YAML + ".bak");
        //noinspection ResultOfMethodCallIgnored
        yamlFileBak.delete();//from  ww w  .  j  ava2 s  .c om
        if (sequenceYaml.exists()) {
            //noinspection ResultOfMethodCallIgnored
            sequenceYaml.renameTo(yamlFileBak);
        }
    }

    try {
        FileUtils.write(sequenceYaml, StationTaskUtils.toString(task), Charsets.UTF_8, false);
    } catch (IOException e) {
        log.error("Error", e);
        throw new IllegalStateException("Error while writing to file: " + sequenceYaml.getPath(), e);
    }
    return task;
}

From source file:com.giri.target.svr.SeleniumTestRunner.java

/**
 * @param driver2/* w w w.  ja  v  a  2 s.  co  m*/
 * @return 
 */
private String captureScreen(TARGetPageDriver driver2) {

    String outputpath = "Screenshot not catpured";

    if (webdriver instanceof TakesScreenshot) {
        File out = ((TakesScreenshot) webdriver).getScreenshotAs(OutputType.FILE);

        final String fileid = UUID.randomUUID().toString();
        final File file = new File("./", fileid + ".png");

        out.renameTo(file);

        outputpath = out.getAbsolutePath();

    } else {
        outputpath = "Screenshot not supported:[" + webdriver.getClass() + "]";
    }

    return outputpath;
}

From source file:com.github.cmisbox.core.Queue.java

private void synchAllWatches() throws Exception {
    Storage storage = Storage.getInstance();
    CMISRepository cmisRepository = CMISRepository.getInstance();
    UI ui = UI.getInstance();//from  w  w w  . ja v a  2 s  .c om
    Config config = Config.getInstance();

    if (ui.isAvailable()) {
        ui.setStatus(Status.SYNCH);
    }

    List<String[]> updates = new ArrayList<String[]>();

    Changes changes = cmisRepository.getContentChanges(storage.getRootIds());

    LinkedHashMap<String, File> downloadList = new LinkedHashMap<String, File>();

    boolean errors = false;

    for (ChangeItem item : changes.getEvents()) {
        try {
            if (item == null) {
                continue;
            }
            String id = "workspace://SpacesStore/" + item.getId();
            String type = item.getT();
            StoredItem storedItem = storage.findById(id);
            if (type.equals("D")) {
                if (storedItem != null) {
                    File f = new File(config.getWatchParent() + storedItem.getPath());
                    f.delete();
                    storage.delete(storedItem, true);
                }
            } else if (type.equals("C") || type.equals("U")) {
                CmisObject remoteObject = cmisRepository.findObject(id);
                remoteObject.refresh();
                if (remoteObject.getType().getBaseTypeId().equals(BaseTypeId.CMIS_FOLDER)) {
                    Folder folder = (Folder) remoteObject;
                    File newFile = new File(this.resolvePath(folder.getFolderParent()), folder.getName());
                    if (storedItem == null) {
                        storage.add(newFile, folder, false);
                    } else {
                        if ((folder.getLastModificationDate().getTimeInMillis() > storedItem
                                .getRemoteModified()) && !storedItem.getName().equals(folder.getName())) {
                            if (new File(storedItem.getAbsolutePath()).renameTo(newFile)) {
                                storage.localUpdate(storedItem, newFile, folder);
                            } else {
                                if (ui.isAvailable()) {
                                    ui.notify(Messages.renameError + " " + storedItem.getAbsolutePath() + " -> "
                                            + newFile.getAbsolutePath());
                                }
                                this.log.error("Unable to rename " + storedItem.getAbsolutePath() + " to "
                                        + newFile.getAbsolutePath());

                            }
                        }
                    }
                } else {
                    Document document = (Document) remoteObject;
                    this.log.debug("preparing to update or create " + document.getName());
                    File newFile = new File(this.resolvePath(document.getParents().get(0)), document.getName());
                    if (storedItem == null) {
                        downloadList.put(id, newFile);
                    } else {
                        File current = new File(storedItem.getAbsolutePath());
                        if (storedItem.getLocalModified() < document.getLastModificationDate()
                                .getTimeInMillis()) {
                            if (!current.getAbsolutePath().equals(newFile.getAbsolutePath())) {
                                if (!current.renameTo(newFile)) {
                                    if (ui.isAvailable()) {
                                        ui.notify(Messages.renameError + " " + storedItem.getAbsolutePath()
                                                + " -> " + newFile.getAbsolutePath());
                                    }
                                    this.log.error("Unable to rename " + storedItem.getAbsolutePath() + " to "
                                            + newFile.getAbsolutePath());
                                }
                            }
                            downloadList.put(id, newFile);
                        }
                    }
                }
            }
        } catch (Exception e1) {
            errors = true;
            this.log.error("Error getting remote chahges for " + item, e1);
        }
    }

    if (ui.isAvailable() && (downloadList.size() > 0)) {
        ui.notify(Messages.downloading + " " + downloadList.size() + " " + Messages.files);
    }
    for (Entry<String, File> e : downloadList.entrySet()) {
        try {
            storage.deleteById(e.getKey());
            e.getValue().delete();
            cmisRepository.download(cmisRepository.getDocument(e.getKey()), e.getValue());
            storage.add(e.getValue(), cmisRepository.getDocument(e.getKey()));
        } catch (Exception e1) {
            errors = true;
            this.log.error("Error downloading " + e, e1);
            if (ui.isAvailable()) {
                ui.notify(Messages.errorDownloading + " " + e);
            }
        }
    }

    if (!errors) {
        config.setChangeLogToken(changes.getToken());
    }

    if (ui.isAvailable()) {
        ui.setStatus(Status.OK);
        if (updates.size() == 1) {
            ui.notify(updates.get(0)[0] + " " + Messages.updatedBy + " " + updates.get(0)[1]);
        } else if (updates.size() > 1) {
            ui.notify(Messages.updated + " " + updates.size() + Messages.files);
        }

    }
}

From source file:com.cloudera.sqoop.orm.CompilationManager.java

/**
 * Compile the .java files into .class files via embedded javac call.
 * On success, move .java files to the code output dir.
 *///from   ww w.  j a v a2 s.  c  o  m
public void compile() throws IOException {
    List<String> args = new ArrayList<String>();

    // ensure that the jar output dir exists.
    String jarOutDir = options.getJarOutputDir();
    File jarOutDirObj = new File(jarOutDir);
    if (!jarOutDirObj.exists()) {
        boolean mkdirSuccess = jarOutDirObj.mkdirs();
        if (!mkdirSuccess) {
            LOG.debug("Warning: Could not make directories for " + jarOutDir);
        }
    } else if (LOG.isDebugEnabled()) {
        LOG.debug("Found existing " + jarOutDir);
    }

    // Make sure jarOutDir ends with a '/'.
    if (!jarOutDir.endsWith(File.separator)) {
        jarOutDir = jarOutDir + File.separator;
    }

    // find hadoop-*-core.jar for classpath.
    String coreJar = findHadoopCoreJar();
    if (null == coreJar) {
        // Couldn't find a core jar to insert into the CP for compilation.  If,
        // however, we're running this from a unit test, then the path to the
        // .class files might be set via the hadoop.alt.classpath property
        // instead. Check there first.
        String coreClassesPath = System.getProperty("hadoop.alt.classpath");
        if (null == coreClassesPath) {
            // no -- we're out of options. Fail.
            throw new IOException("Could not find hadoop core jar!");
        } else {
            coreJar = coreClassesPath;
        }
    }

    // find sqoop jar for compilation classpath
    String sqoopJar = Jars.getSqoopJarPath();
    if (null != sqoopJar) {
        sqoopJar = File.pathSeparator + sqoopJar;
    } else {
        LOG.warn("Could not find sqoop jar; child compilation may fail");
        sqoopJar = "";
    }

    String curClasspath = System.getProperty("java.class.path");

    args.add("-sourcepath");
    args.add(jarOutDir);

    args.add("-d");
    args.add(jarOutDir);

    args.add("-classpath");
    args.add(curClasspath + File.pathSeparator + coreJar + sqoopJar);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (null == compiler) {
        LOG.error("It seems as though you are running sqoop with a JRE.");
        LOG.error("Sqoop requires a JDK that can compile Java code.");
        LOG.error("Please install a JDK and set $JAVA_HOME to use it.");
        throw new IOException("Could not start Java compiler.");
    }
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    ArrayList<String> srcFileNames = new ArrayList<String>();
    for (String srcfile : sources) {
        srcFileNames.add(jarOutDir + srcfile);
        LOG.debug("Adding source file: " + jarOutDir + srcfile);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Invoking javac with args:");
        for (String arg : args) {
            LOG.debug("  " + arg);
        }
    }

    Iterable<? extends JavaFileObject> srcFileObjs = fileManager.getJavaFileObjectsFromStrings(srcFileNames);
    JavaCompiler.CompilationTask task = compiler.getTask(null, // Write to stderr
            fileManager, null, // No special diagnostic handling
            args, null, // Compile all classes in the source compilation units
            srcFileObjs);

    boolean result = task.call();
    if (!result) {
        throw new IOException("Error returned by javac");
    }

    // Where we should move source files after compilation.
    String srcOutDir = new File(options.getCodeOutputDir()).getAbsolutePath();
    if (!srcOutDir.endsWith(File.separator)) {
        srcOutDir = srcOutDir + File.separator;
    }

    // Move these files to the srcOutDir.
    for (String srcFileName : sources) {
        String orig = jarOutDir + srcFileName;
        String dest = srcOutDir + srcFileName;
        File fOrig = new File(orig);
        File fDest = new File(dest);
        File fDestParent = fDest.getParentFile();
        if (null != fDestParent && !fDestParent.exists()) {
            if (!fDestParent.mkdirs()) {
                LOG.error("Could not make directory: " + fDestParent);
            }
        }

        if (!fOrig.renameTo(fDest)) {
            LOG.error("Could not rename " + orig + " to " + dest);
        }
    }
}

From source file:com.photon.phresco.plugins.JavaPackage.java

private void copyWarToPackage(String zipNameWithoutExt, String context) throws MojoExecutionException {
    try {/*w w w .  jav a2s.  co m*/
        String[] list = targetDir.list(new WarFileNameFilter());
        if (list.length > 0) {
            File warFile = new File(targetDir.getPath() + File.separator + list[0]);
            tempDir = new File(buildDir.getPath() + File.separator + zipNameWithoutExt);
            tempDir.mkdir();
            File contextWarFile = new File(targetDir.getPath() + File.separator + context + ".war");
            warFile.renameTo(contextWarFile);
            FileUtils.copyFileToDirectory(contextWarFile, tempDir);
        } else {
            throw new MojoExecutionException("Compilation Failure...");
        }
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:com.ecyrd.jspwiki.providers.WikiVersioningFileProvider.java

@Override
public void movePage(String from, String to) throws ProviderException {
    // Rename in database
    try {//from w  ww  .  j  a  v a 2 s.c  o  m
        pageDAO.renamePage(from, to, WikiMultiInstanceManager.getComponentId());
    } catch (WikiException e) {
        SilverTrace.error("wiki", "WikiVersioningFileProvider.movePage()", "wiki.EX_MOVE_PAGE", e);
        throw new ProviderException("Could not move page");
    }

    // Move the file itself
    File fromFile = findPage(from);
    File toFile = findPage(to);
    fromFile.renameTo(toFile);
    // Move any old versions
    File fromOldDir = findOldPageDir(from);
    File toOldDir = findOldPageDir(to);
    fromOldDir.renameTo(toOldDir);
}

From source file:com.funambol.foundation.util.FileSystemDAOHelper.java

/**
 * Renames file1 in file2// ww  w. j a  va2  s.  c o  m
 * @param file1
 * @param file2
 * @return true if and only if the renaming succeeded
 * @throws IOException
 */
public boolean renameFile(File file1, File file2) throws IOException {
    return file1.renameTo(file2);
}

From source file:net.sourceforge.dvb.projectx.common.Common.java

public static boolean renameTo(File oldfile, File newfile) {
    //explicit call, otherwise java >= 1.5 ? doesnt release a closed file object immediately
    System.gc();/*from  w w w .  j  ava2  s.  c om*/

    for (int i = 0; i < 10000; i++)
        if (oldfile.renameTo(newfile))
            return true;

    setMessage(
            Resource.getString("common.rename_error1") + " '" + oldfile.toString() + "' "
                    + Resource.getString("common.rename_error2") + " '" + newfile.toString() + "'",
            true, 0xFFE0E0);

    return false;
}

From source file:ninja.leaping.permissionsex.backend.file.FileDataStore.java

private File migrateLegacy(File permissionsFile, String extension, ConfigurationLoader<?> loader,
        String formatName) throws PermissionsLoadingException {
    File legacyPermissionsFile = permissionsFile;
    file = file.replace(extension, ".json");
    permissionsFile = new File(getManager().getBaseDirectory(), file);
    permissionsFileLoader = createLoader(permissionsFile);
    try {/*from   w  w w  .j  a  va 2  s.  c  o  m*/
        permissionsConfig = loader.load();
        permissionsFileLoader.save(permissionsConfig);
        legacyPermissionsFile.renameTo(new File(legacyPermissionsFile.getCanonicalPath() + ".legacy-backup"));
    } catch (IOException e) {
        throw new PermissionsLoadingException(
                _("While loading legacy %s permissions from %s", formatName, permissionsFile), e);
    }
    return permissionsFile;
}

From source file:com.ms.commons.standalone.pojo.StandaloneJob.java

/**
 * fullClassName conf????job//from  www  .  ja  v a 2 s  . co m
 */
private synchronized void modifyDataSourceProperties(String fullClassName, String identity,
        String baseStandalonePath) throws Exception {
    if (StringUtils.contains(fullClassName, "msun")) {
        String filePath = baseStandalonePath + "/conf/msun.datasource.properties";
        String tmpFile = filePath + ".tmp";
        File file = new File(filePath);
        File tmp = new File(tmpFile);
        tmp.createNewFile();
        if (file.exists()) {
            BufferedReader buffRead = new BufferedReader(new FileReader(file));
            BufferedWriter write = new BufferedWriter(new FileWriter(tmp));
            String content = null;
            while ((content = buffRead.readLine()) != null) {
                if (StringUtils.contains(content, "nisa.client.appname")) {
                    content = "nisa.client.appname=" + identity;
                }
                write.write(content);
                write.newLine();
            }
            write.close();
            buffRead.close();
        }
        tmp.renameTo(file);
    }
}