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:psiprobe.model.stats.StatsCollection.java

/**
 * Shift files.//from w  ww  .  j  ava2  s . c o  m
 *
 * @param index the index
 */
private void shiftFiles(int index) {
    if (index >= maxFiles - 1) {
        new File(makeFile().getAbsolutePath() + "." + index).delete();
    } else {
        shiftFiles(index + 1);
        File srcFile = index == 0 ? makeFile() : new File(makeFile().getAbsolutePath() + "." + index);
        File destFile = new File(makeFile().getAbsolutePath() + "." + (index + 1));
        srcFile.renameTo(destFile);
    }
}

From source file:com.qwazr.store.store.StoreService.java

@PUT
@Path("/{path : .+}")
public Response put(@Context UriInfo uriInfo, @PathParam("path") String path, InputStream inputStream)
        throws IOException {
    File file = StoreManager.INSTANCE.getFile(path);
    if (file.exists() && file.isDirectory())
        return responseText(Status.CONFLICT, "Error. A directory already exists: " + path).build();
    File tmpFile = File.createTempFile("oss-cluster-node", ".upload");
    FileOutputStream fos = null;//from w ww.j a  v  a  2 s  . c  o m
    try {
        fos = new FileOutputStream(tmpFile);
        IOUtils.copy(inputStream, fos);
        fos.close();
        if (file.exists())
            file.delete();
        tmpFile.renameTo(file);
        tmpFile = null;
        return new FileItem(file).headerResponse(Response.status(Status.OK)).build();
    } finally {
        if (fos != null)
            IOUtils.closeQuietly(fos);
        if (tmpFile != null)
            tmpFile.delete();
    }
}

From source file:ai.susi.json.JsonRepository.java

/**
 * move a file from the import directory to the imported directory.
 * @param dumpName only the name, not the full path. The file must be in the import file path
 * @return true if the file was shifted successfully, false if file did not exist or cannot be moved
 *///w  w  w  . j a  v  a  2 s .c  om
public boolean shiftProcessedDump(String dumpName) {
    File f = new File(this.dump_dir_import, dumpName);
    if (!f.exists())
        return false;
    File g = new File(this.dump_dir_imported, dumpName);
    if (g.exists())
        g.delete();
    return f.renameTo(g);
}

From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

public KeyStoreObjects getKeyStoreObjects(String reserver) {
    String keyStoreId = "";
    File privateKsFile = new File(tempKeyStoreDir, reserver);
    File[] listFiles = new File(keyStoreDir).listFiles(noLeadingDot);
    int cnt = listFiles.length;
    int select = rng.nextInt(cnt);
    File selected;
    boolean success = false;
    // try to claim a ks file;
    try {/*from w w  w.  j av a2s. c  o  m*/
        selected = listFiles[select];
        keyStoreId = selected.getName();
        selected.renameTo(privateKsFile);
        success = privateKsFile.canRead();
    } catch (Exception ex) {
    }
    // If not successful - generate a new key store
    if (!success) {
        createKeyStore(privateKsFile);
        keyStoreId = reserver;
    }

    try {
        KeyStore ks = getKeyStore(privateKsFile, keyStoreId);
        PrivateKey pk = (PrivateKey) ks.getKey(K_NAME, getKsPass(keyStoreId));
        Certificate cert = ks.getCertificate(K_NAME);
        iaik.x509.X509Certificate x509cert = CertificateUtils.getCertificate(cert.getEncoded());
        privateKsFile.delete();
        return new KeyStoreObjects(pk, x509cert);
    } catch (Exception ex) {
        LOG.log(Level.WARNING, null, ex);
        privateKsFile.delete();
        return null;
    }
}

From source file:com.o2d.pkayjava.editor.data.migrations.migrators.VersionMigTo005.java

@Override
public boolean doMigration() {

    // Rename folder animations to spine-animations in orig (if exist);
    File animationsDir = new File(
            projectPath + File.separator + "assets" + File.separator + "orig" + File.separator + "animations");
    if (animationsDir.exists() && animationsDir.isDirectory()) {
        File spineAnimationsDir = new File(projectPath + File.separator + "assets" + File.separator + "orig"
                + File.separator + "spine-animations");
        animationsDir.renameTo(spineAnimationsDir);
    }/*from   ww w .j  a  v a2  s  .  c  o  m*/

    // get list of resolutions
    String prjInfoFilePath = projectPath + "/project.dt";
    FileHandle projectInfoFile = Gdx.files.internal(prjInfoFilePath);
    String projectInfoContents = null;
    try {
        projectInfoContents = FileUtils.readFileToString(projectInfoFile.file());
        ProjectInfoVO currentProjectInfoVO = json.fromJson(ProjectInfoVO.class, projectInfoContents);
        projectManager.currentProjectInfoVO = currentProjectInfoVO;

        // run through all resolutions and remake animations for all
        for (ResolutionEntryVO resolutionEntryVO : currentProjectInfoVO.resolutions) {
            ResolutionManager resolutionManager = facade.retrieveProxy(ResolutionManager.NAME);
            resolutionManager.createResizedAnimations(resolutionEntryVO);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // change sLights to sLights
    File scenesDir = new File(projectPath + File.separator + "scenes");
    for (File entry : scenesDir.listFiles()) {
        if (!entry.isDirectory()) {
            try {
                String content = FileUtils.readFileToString(new FileHandle(entry).file());
                content = content.replaceAll("\"slights\":", "\"sLights\":");
                FileUtils.writeStringToFile(new File(entry.getAbsolutePath()), content, "utf-8");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    return true;
}

From source file:io.treefarm.plugins.haxe.CompileHxcppMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    super.execute();

    File projectFile;//  w  ww. j  a  v a  2  s.c  om

    if (cacheFiles != null) {
        File cacheFile;
        for (String cacheFileName : cacheFiles) {
            getLog().info("Deleting cache '" + cacheFileName + "'.");
            cacheFile = new File(cacheFileName);
            FileUtils.deleteQuietly(cacheFile);
        }
    }

    if (hxcppProjectFile != null) {
        projectFile = new File(hxcppProjectFile);
        if (projectFile.exists()) {
            getLog().info("Building Hxcpp project '" + projectFile.getName() + "'.");
            try {
                hxcppCompiler.initialize(debug);
                hxcppCompiler.compile(project, projectFile, projectFile.getParentFile(), compilerFlags);
            } catch (Exception e) {
                throw new MojoFailureException("Hxcpp build failed ", e);
            }

            if (relocateFiles != null && relocateFiles.containsKey("source")
                    && relocateFiles.containsKey("destination")) {
                try {
                    File source = new File(relocateFiles.get("source"));
                    File destination = new File(relocateFiles.get("destination"));
                    if (source.exists()) {
                        getLog().info("Relocating '" + source.getAbsolutePath() + "' to '"
                                + destination.getAbsolutePath() + "'");
                        source.renameTo(destination);
                    } else {
                        getLog().error("Hxcpp relocate cannot move '" + source.getAbsolutePath()
                                + "' as it appears not to exist!");
                    }
                } catch (Exception e) {
                    throw new MojoFailureException("Hxcpp relocate failed ", e);
                }
            }
        } else {
            throw new MojoFailureException(
                    "Hxcpp project file '" + projectFile.getName() + "' does not exist!");
        }
    }
}

From source file:com.adaptris.core.fs.FsConsumer.java

private void renameWipFiles() throws Exception {
    URL urlDestination = FsHelper.createUrlFromString(getDestination().getDestination(), true);
    File dir = FsHelper.createFileReference(urlDestination);
    if (!dir.exists()) {
        // No point because it doesn't exist.
        return;/*from  w ww.  j a v  a2  s .c o m*/
    }
    RegexFileFilter p5 = new RegexFileFilter(".*\\" + getWipSuffix());
    File[] files = dir.listFiles((FilenameFilter) p5);
    if (files == null) {
        throw new CoreException("Failed to list files in " + dir.getCanonicalPath()
                + ", incorrect permissions?. Cannot reset WIP files");
    }
    for (File f : files) {
        File parent = f.getParentFile();
        String name = f.getName().replaceAll(getWipSuffix().replaceAll("\\.", "\\\\."), "");
        log.trace("Will Rename " + f.getName() + " back to " + name);
        File newFile = new File(parent, name);
        f.renameTo(newFile);
    }
}

From source file:com.android.build.gradle.integration.application.ExternalBuildPluginTest.java

@Test
public void testBuild() throws ProcessException, IOException, ParserConfigurationException, SAXException {
    FileUtils.write(mProject.getBuildFile(),
            "" + "apply from: \"../commonHeader.gradle\"\n" + "buildscript {\n "
                    + "  apply from: \"../commonBuildScript.gradle\"\n" + "}\n" + "\n"
                    + "apply plugin: 'base'\n" + "apply plugin: 'com.android.external.build'\n" + "\n"
                    + "externalBuild {\n" + "  executionRoot = $/" + mProject.getTestDir().getAbsolutePath()
                    + "/$\n" + "  buildManifestPath = $/" + manifestFile.getAbsolutePath() + "/$\n" + "}\n");

    mProject.executor().withInstantRun(23, ColdswapMode.AUTO).withPackaging(mPackaging).run("clean", "process");

    InstantRunBuildContext instantRunBuildContext = loadFromBuildInfo();
    assertThat(instantRunBuildContext.getPreviousBuilds()).hasSize(1);
    assertThat(instantRunBuildContext.getLastBuild()).isNotNull();
    assertThat(instantRunBuildContext.getLastBuild().getArtifacts()).hasSize(1);
    InstantRunBuildContext.Build fullBuild = instantRunBuildContext.getLastBuild();
    assertThat(fullBuild.getVerifierStatus().get()).isEqualTo(InstantRunVerifierStatus.INITIAL_BUILD);
    assertThat(fullBuild.getArtifacts()).hasSize(1);
    InstantRunBuildContext.Artifact artifact = fullBuild.getArtifacts().get(0);
    assertThat(artifact.getType()).isEqualTo(InstantRunBuildContext.FileType.MAIN);
    assertThat(artifact.getLocation().exists()).isTrue();

    ApkSubject apkSubject = expect.about(ApkSubject.FACTORY).that(artifact.getLocation());
    apkSubject.contains("instant-run.zip");
    assertThat(apkSubject.hasMainDexFile());

    // now perform a hot swap test.
    File mainClasses = new File(mProject.getTestDir(), "jars/main/classes.jar");
    assertThat(mainClasses.exists()).isTrue();

    File originalFile = new File(mainClasses.getParentFile(), "original_classes.jar");
    assertThat(mainClasses.renameTo(originalFile)).isTrue();

    try (JarFile inputJar = new JarFile(originalFile);
            JarOutputStream jarOutputFile = new JarOutputStream(new BufferedOutputStream(
                    new FileOutputStream(new File(mainClasses.getParentFile(), "classes.jar"))))) {
        Enumeration<JarEntry> entries = inputJar.entries();
        while (entries.hasMoreElements()) {
            JarEntry element = entries.nextElement();
            try (InputStream inputStream = new BufferedInputStream(inputJar.getInputStream(element))) {
                if (!element.isDirectory()) {
                    jarOutputFile.putNextEntry(new ZipEntry(element.getName()));
                    try {
                        if (element.getName().contains("MainActivity.class")) {
                            // perform hot swap change
                            byte[] classBytes = new byte[(int) element.getSize()];
                            ByteStreams.readFully(inputStream, classBytes);
                            classBytes = hotswapChange(classBytes);
                            jarOutputFile.write(classBytes);
                        } else {
                            ByteStreams.copy(inputStream, jarOutputFile);
                        }/* ww  w. j  a  va  2s  . co m*/
                    } finally {
                        jarOutputFile.closeEntry();
                    }
                }
            }
        }
    }

    mProject.executor().withInstantRun(23, ColdswapMode.AUTO).withPackaging(mPackaging).run("process");

    instantRunBuildContext = loadFromBuildInfo();
    assertThat(instantRunBuildContext.getPreviousBuilds()).hasSize(2);
    InstantRunBuildContext.Build lastBuild = instantRunBuildContext.getLastBuild();
    assertThat(lastBuild).isNotNull();
    assertThat(lastBuild.getVerifierStatus().isPresent());
    assertThat(lastBuild.getVerifierStatus().get()).isEqualTo(InstantRunVerifierStatus.COMPATIBLE);
    assertThat(lastBuild.getArtifacts()).hasSize(1);
    artifact = lastBuild.getArtifacts().get(0);
    assertThat(artifact.getType()).isEqualTo(InstantRunBuildContext.FileType.RELOAD_DEX);
    assertThat(artifact.getLocation()).isNotNull();
    File dexFile = artifact.getLocation();
    assertThat(dexFile.exists()).isTrue();
    DexFileSubject reloadDex = expect.about(DexFileSubject.FACTORY).that(dexFile);
    reloadDex.hasClass("Lcom/android/tools/fd/runtime/AppPatchesLoaderImpl;").that();
    reloadDex.hasClass("Lcom/example/jedo/blazeapp/MainActivity$override;").that();
}

From source file:Commands.AddShoesCommand.java

@Override
public String executeCommand(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String forwardToJsp = "";
    HttpSession session = request.getSession(true);
    ShoesDao sd = new ShoesDao();
    boolean check = true;
    ArrayList<String> addList = new ArrayList<>();
    ArrayList<Shoes> list = new ArrayList<>();
    HashMap<Integer, LinkedList<String>> status = new HashMap<>();
    HashMap<Integer, LinkedList<Integer>> color = new HashMap<>();
    LinkedList<String> s = null;
    LinkedList<Integer> c = null;
    if (session.getAttribute("userLogin") != null && ((User) session.getAttribute("userLogin")).is_Admin()) {
        if (request.getParameter("number") != null) {
            int num = Integer.parseInt(request.getParameter("number"));
            for (int n = 1; n < num; n++) {
                s = new LinkedList<>();
                c = new LinkedList<>();
                boolean check1 = true;
                if (request.getParameter("name-" + n) != null && request.getParameter("brand-" + n) != null
                        && request.getParameter("sport-" + n) != null) {
                    if (request.getParameter("name-" + n).isEmpty()) {
                        session.setAttribute("errorMsg", "The name cannot be empty");
                        return forwardToJsp = "AddShoes.jsp";
                    }//from w ww .  jav  a 2 s . c o  m
                    String name = (String) request.getParameter("name-" + n).substring(0, 1).toUpperCase()
                            + request.getParameter("name-" + n).substring(1).toLowerCase();
                    int brand = Integer.parseInt(request.getParameter("brand-" + n));
                    int sport = Integer.parseInt(request.getParameter("sport-" + n));
                    if (request.getParameter("price-" + n).isEmpty()) {
                        s.add("price cannot be empty");
                    }
                    double price = Double.parseDouble(request.getParameter("price-" + n));
                    if (price < 1 || price > 200) {
                        s.add("price range is between 1 to 200");
                    }
                    if (!sd.findShoes(name).isEmpty()) {
                        s.add("The name is repeated");
                    }

                    boolean repeat = false;
                    for (int i = 1; i < 4; i++) {
                        if (request.getParameter("color" + i + "-" + n) != null) {
                            int id = Integer.parseInt(request.getParameter("color" + i + "-" + n));
                            if (c.contains(id)) {
                                repeat = true;
                            }
                            c.add(id);
                        }
                    }
                    if (repeat) {
                        s.add("The color is repeated");
                    }

                    //                        String[] files1 = request.getParameterValues("file1-" + n);
                    //                        String[] files2 = request.getParameterValues("file2-" + n);
                    //                        String[] files3 = request.getParameterValues("file3-" + n);
                    //                        long a=Arrays.stream(files1).filter((String st) -> !st.isEmpty()).count();
                    //                        long b=Arrays.stream(files1).filter((String st) -> !st.isEmpty()).count();
                    //                        long d=Arrays.stream(files1).filter((String st) -> !st.isEmpty()).count();
                    //                        if(a==0 || b==0 || d==0){
                    //                            s.add("Images is not uploaded");
                    //                        }
                    //                        p.add(files1);
                    //                        p.add(files2);
                    //                        p.add(files3);
                    if (!s.isEmpty()) {
                        status.put(n, s);
                    }
                    color.put(n, c);
                    list.add(new Shoes(n, brand, 0, sport, name, price, ""));
                } else {
                    check = false;
                    break;
                }
            }
            ColorDao cd = new ColorDao();

            response.setContentType("text/html");
            session.setAttribute("list", list);
            session.setAttribute("status", status);
            session.setAttribute("allcolor", color);
            if (status.isEmpty() && check) {
                for (int i = 0; i < list.size(); i++) {
                    c = color.get(i + 1);
                    Iterator<Integer> iter = c.iterator();
                    int count = 1;

                    while (iter.hasNext()) {
                        String name = list.get(i).getName();
                        int colorId = iter.next();
                        String colorName = cd.findColorById(colorId).getColor_Name();
                        String pic = name + "-" + colorName + "-";
                        sd.addShoes(list.get(i).getBrandID(), colorId, list.get(i).getTypeID(), name,
                                list.get(i).getPrice(), pic);
                        String colo = request.getParameter("cr" + count + "-" + (i + 1));
                        String[] col = colo.split(",");
                        String UPLOAD_DIRECTORY = request.getServletContext().getRealPath("") + File.separator
                                + "img" + File.separator;
                        int count1 = 1;
                        for (String str : col) {
                            File file = new File(UPLOAD_DIRECTORY + str.substring(4));
                            File f = new File(UPLOAD_DIRECTORY + pic + count1 + ".jpg");
                            try {
                                boolean check1 = file.renameTo(f);
                                if (check1 == false) {
                                    session.setAttribute("errorMsg",
                                            str.substring(4) + " " + UPLOAD_DIRECTORY + pic);
                                    return "AddShoes.jsp";
                                }
                            } catch (SecurityException | NullPointerException se) {
                                session.setAttribute("errorMsg", Arrays.toString(se.getStackTrace()));
                                return "AddShoes.jsp";

                            }
                            count1++;
                        }
                        count++;

                    }
                }
                session.setAttribute("errorMsg", "Shoes is successful added");
                //                    session.removeAttribute("list");
                //                    session.removeAttribute("allcolor");
                //                    session.removeAttribute("status");

            } else {
                session.setAttribute("errorMsg", "Please fill the form with correct information");
                forwardToJsp = "AddShoes.jsp";
            }

        } else {
            session.setAttribute("errorMsg", "Fail to save changes, please refresh the page and try again");
            forwardToJsp = "shoes.jsp";
        }
    } else {
        session.setAttribute("errorMsg", "You are not allowed to access this page");
        forwardToJsp = "index.jsp";
    }
    return forwardToJsp;
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.localworkspace.LocalMetadataTable.java

/**
 * Move the written file in slot 3 to slot 2, then to slot 1.
 */// w  w  w.j  a v a2  s .c o m
private void positionFile(final boolean keepFile) {
    final String slotOneFilename = getSlotOnePath(filename);
    final String slotTwoFilename = getSlotTwoPath(filename);
    final String slotThreeFilename = getSlotThreePath(filename);

    final File slotOneFile = new File(slotOneFilename);
    final File slotTwoFile = new File(slotTwoFilename);
    final File slotThreeFile = new File(slotThreeFilename);

    /* Move slot three file into slot two */
    slotTwoFile.delete();

    if (!slotThreeFile.renameTo(slotTwoFile)) {
        throw new RuntimeException(
                MessageFormat.format("Could not rename {0} to {1}", slotThreeFilename, slotTwoFilename)); //$NON-NLS-1$
    }

    /* Move slot two file into slot one */
    slotOneFile.delete();
    renameFile(slotTwoFile, slotOneFile);
}