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:edu.monash.merc.util.file.DMFileUtils.java

public static void moveFile(File srcFile, File destFile, boolean override) {
    try {/*from   w ww .ja  v a 2s .  com*/
        if (srcFile == null) {
            throw new NullPointerException("Source file must not be null");
        }

        if (destFile == null) {
            throw new NullPointerException("Destination file 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() && !override) {
            throw new FileExistsException("Destination '" + destFile + "' already exists");
        }
        if (destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' is a directory");
        }
        boolean rename = srcFile.renameTo(destFile);
        if (!rename) {
            copyFile(srcFile, destFile, true);
            if (!srcFile.delete()) {
                FileUtils.deleteQuietly(destFile);
                throw new IOException(
                        "Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'");
            }
        }
    } catch (Exception e) {
        throw new DMFileException(e);
    }
}

From source file:Controlador.imagenes.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w  .  j  ava 2  s  .  c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException {

    String archivourl = "D:\\Carlos Ivn\\Desktop\\CMSProductos\\web\\recursos\\imagenes\\index";

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setSizeThreshold(1024);

    factory.setRepository(new File(archivourl));

    ServletFileUpload upload = new ServletFileUpload(factory);
    String cod = "";

    PrintWriter out = response.getWriter();

    try {

        String nom = "";
        List<FileItem> partes = upload.parseRequest(request);
        Iterator<FileItem> it = partes.iterator();
        FileItem fileItem = it.next();
        if ("txtImagen1".equals(fileItem.getFieldName())) {
            nom = "\\c1.jpg";
        } else if ("txtImagen2".equals(fileItem.getFieldName())) {
            nom = "\\ca2.jpg";
        } else if ("txtImagen3".equals(fileItem.getFieldName())) {
            nom = "\\ca3.jpg";
        } else if ("txtImagenn".equals(fileItem.getFieldName())) {
            archivourl = "D:\\Carlos Ivn\\Desktop\\CMSProductos\\web\\recursos\\imagenes\\nosotros";
            nom = "\\portada.jpg";
        }
        out.print(fileItem.getFieldName());
        for (FileItem items : partes) {
            File file = new File(archivourl, items.getName());
            String ruta = archivourl + "\\" + items.getName();
            String ruta2 = archivourl + nom;
            out.println(ruta);
            // verificar si existe el nombre y borrarlo
            if (ruta == null ? ruta2 != null : !ruta.equals(ruta2)) {
                File file2 = new File(ruta2);
                file2.delete();
            }
            //  cambiar el nombre del archivo    
            items.write(file);
            File archivo = new File(ruta);
            archivo.renameTo(new File(ruta2));

        }
        if (nom == "\\portada.jpg") {
            response.sendRedirect("Administrador/Paginas/nosotros.jsp");
        } else
            response.sendRedirect("Administrador/Paginas/inicio.jsp");
    } catch (Exception e) {
        out.print("ERROR " + e.getMessage() + "");
        //response.sendRedirect("Administrador/Paginas/inicio.jsp");
    }
}

From source file:be.roots.taconic.pricingguide.service.ReportServiceImpl.java

@Override
public void archive(String lastMonthsReportFileName) {
    final File lastMonthsReportFile = new File(lastMonthsReportFileName);
    if (lastMonthsReportFile.exists()) {
        lastMonthsReportFile.renameTo(new File(lastMonthsReportFile + ".sent"));
    }/*from www .  j  av a  2s. c o m*/
}

From source file:git.egatuts.android.FileUtils.EgaFileSystem.java

/**
 * (non-Javadoc)//from   www .jav  a 2s  .  c  o  m
 * @see git.egatuts.android.FileUtils.EgaFileSystemBase#deleteFile(java.io.File)
 */
@Override
public void deleteFile(File file) throws IOException {
    File deletedName = new File(file.getAbsolutePath() + System.currentTimeMillis());
    file.renameTo(deletedName);
    if (!file.isFile()) {
        file.delete();
        return;
    }
    FileUtils.deleteDirectory(file);
}

From source file:com.ichi2.libanki.sync.FullSyncer.java

@Override
public Object[] download() throws UnknownHttpResponseException {
    InputStream cont;// w  ww .j a  va2s . c o m
    try {
        HttpResponse ret = super.req("download");
        if (ret == null) {
            return null;
        }
        cont = ret.getEntity().getContent();
    } catch (IllegalStateException e1) {
        throw new RuntimeException(e1);
    } catch (IOException e1) {
        return null;
    }
    if (mCol == null) {
        Timber.e("Collection was unexpectedly null");
        return null;
    }
    String path = mCol.getPath();
    mCol.close(false);
    mCol = null;
    String tpath = path + ".tmp";
    try {
        super.writeToFile(cont, tpath);
    } catch (IOException e) {
        Timber.e(e, "Full sync failed to download collection.");
        return new Object[] { "sdAccessError" };
    }
    // first check, if account needs upgrade (from 1.2)
    try {
        FileInputStream fis = new FileInputStream(tpath);
        if (super.stream2String(fis, 15).equals("upgradeRequired")) {
            return new Object[] { "upgradeRequired" };
        }
    } catch (FileNotFoundException e1) {
        throw new RuntimeException(e1);
    }
    // check the received file is ok
    mCon.publishProgress(R.string.sync_check_download_file);
    try {
        AnkiDb d = AnkiDatabaseManager.getDatabase(tpath);
        if (!d.queryString("PRAGMA integrity_check").equalsIgnoreCase("ok")) {
            Timber.e("Full sync - downloaded file corrupt");
            return new Object[] { "remoteDbError" };
        }
    } catch (SQLiteDatabaseCorruptException e) {
        Timber.e("Full sync - downloaded file corrupt");
        return new Object[] { "remoteDbError" };
    } finally {
        AnkiDatabaseManager.closeDatabase(tpath);
    }
    // overwrite existing collection
    File newFile = new File(tpath);
    if (newFile.renameTo(new File(path))) {
        return new Object[] { "success" };
    } else {
        return new Object[] { "overwriteError" };
    }
}

From source file:com.amazonaws.auth.profile.ProfilesConfigFileWriter.java

/**
 * A package-private method that supports all kinds of profile modification,
 * including renaming or deleting one or more profiles.
 *
 * @param modifications//from www .ja v  a  2 s .  c  o m
 *            Use null key value to indicate a profile that is to be
 *            deleted.
 */
static void modifyProfiles(File destination, Map<String, Profile> modifications) {
    final boolean inPlaceModify = destination.exists();
    File stashLocation = null;

    // Stash the original file, before we apply the changes
    if (inPlaceModify) {
        boolean stashed = false;

        try {
            // We can't use File.createTempFile, since it will always create
            // that file no matter what, and File.reNameTo does not allow
            // the destination to be an existing file
            stashLocation = new File(destination.getParentFile(),
                    destination.getName() + ".bak." + UUID.randomUUID().toString());
            stashed = destination.renameTo(stashLocation);

            if (LOG.isDebugEnabled()) {
                LOG.debug(String.format("The original credentials file is stashed to loaction (%s).",
                        stashLocation.getAbsolutePath()));
            }

        } finally {
            if (!stashed) {
                throw new AmazonClientException(
                        "Failed to stash the existing credentials file " + "before applying the changes.");
            }
        }
    }

    FileWriter writer = null;
    try {
        writer = new FileWriter(destination);
        ProfilesConfigFileWriterHelper writerHelper = new ProfilesConfigFileWriterHelper(writer, modifications);

        if (inPlaceModify) {
            Scanner existingContent = new Scanner(stashLocation);
            writerHelper.writeWithExistingContent(existingContent);
        } else {
            writerHelper.writeWithoutExistingContent();
        }

        // Make sure the output is valid and can be loaded by the loader
        new ProfilesConfigFile(destination);

        if (inPlaceModify && !stashLocation.delete()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(String.format(
                        "Successfully modified the credentials file. But failed to "
                                + "delete the stashed copy of the original file (%s).",
                        stashLocation.getAbsolutePath()));
            }
        }

    } catch (Exception e) {
        // Restore the stashed file
        if (inPlaceModify) {
            boolean restored = false;

            try {
                // We don't really care about what destination.delete()
                // returns, since the file might not have been created when
                // the error occurred.
                if (!destination.delete()) {
                    LOG.debug("Unable to remove the credentials file " + "before restoring the original one.");
                }
                restored = stashLocation.renameTo(destination);
            } finally {
                if (!restored) {
                    throw new AmazonClientException("Unable to restore the original credentials file. "
                            + "File content stashed in " + stashLocation.getAbsolutePath());
                }
            }
        }

        throw new AmazonClientException(
                "Unable to modify the credentials file. " + "(The original file has been restored.)", e);

    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.meltmedia.cadmium.core.github.ApiClientTest.java

@Before
public void setupForTest() throws Exception {
    File cadmiumDir = new File(System.getProperty("user.home"), ".cadmium");
    File tokenFile = new File(cadmiumDir, "github.token");
    if (tokenFile.exists()) {
        tokenFile.renameTo(new File(cadmiumDir, "github.token.old"));
    }//from  ww  w . j  a  v  a 2  s  . c  om
    if (!tokenFile.exists()) {
        System.out.println("Token file doesn't exist.");
        if (username == null || password == null) {
            username = System.getProperty("github.username");
            password = System.getProperty("github.password");
        }

        if (username == null || password == null) {
            System.err.println(
                    "Please set your github.username and github.password in the java system properties to run these tests.");
            System.err.println("Skipping test!");
            assumeTrue(false);
        }

        List<String> scopes = new ArrayList<String>();
        scopes.add("repo");

        tokenAuth = ApiClient.authorize(username, password, scopes, "Testing");

        assertTrue("Authorization failed.", tokenAuth != null);

        FileSystemManager.writeStringToFile(cadmiumDir.getAbsolutePath(), "github.token", tokenAuth.getToken());
    }
}

From source file:oz.hadoop.yarn.api.core.ApplicationMasterLauncherImplTests.java

@Test
public void validateWithMissingClasspathFilters() throws Exception {
    ClassPathResource res = new ClassPathResource("classpath.filters");
    File cpFilterFile = res.getFile();
    File backup = new File("classpath.filters.old");
    try {//from   www. jav  a2 s .c  o m
        cpFilterFile.renameTo(backup);
        Map<String, Object> applicationSpecification = new HashMap<>();
        applicationSpecification.put(YayaConstants.CONTAINER_SPEC, new HashMap<>());
        ApplicationMasterLauncherImpl<Void> launcher = new ApplicationMasterLauncherImpl<>(
                applicationSpecification);

        Method excludedMethod = ReflectionUtils.getMethodAndMakeAccessible(ApplicationMasterLauncherImpl.class,
                "excluded", String.class);
        String[] cp = System.getProperty("java.class.path").split(":");
        for (String v : cp) {
            File f = new File(v);
            if (!f.isDirectory()) {
                boolean excluded = (boolean) excludedMethod.invoke(launcher, f.getName());
                assertFalse(f.getName(), excluded);
            }
        }
    } finally {
        backup.renameTo(cpFilterFile);
    }
}

From source file:com.ksc.auth.profile.ProfilesConfigFileWriter.java

/**
 * A package-private method that supports all kinds of profile modification,
 * including renaming or deleting one or more profiles.
 *
 * @param modifications/*from  w w w .j  a va 2 s  .c  o m*/
 *            Use null key value to indicate a profile that is to be
 *            deleted.
 */
static void modifyProfiles(File destination, Map<String, Profile> modifications) {
    final boolean inPlaceModify = destination.exists();
    File stashLocation = null;

    // Stash the original file, before we apply the changes
    if (inPlaceModify) {
        boolean stashed = false;

        try {
            // We can't use File.createTempFile, since it will always create
            // that file no matter what, and File.reNameTo does not allow
            // the destination to be an existing file
            stashLocation = new File(destination.getParentFile(),
                    destination.getName() + ".bak." + UUID.randomUUID().toString());
            stashed = destination.renameTo(stashLocation);

            if (LOG.isDebugEnabled()) {
                LOG.debug(String.format("The original credentials file is stashed to loaction (%s).",
                        stashLocation.getAbsolutePath()));
            }

        } finally {
            if (!stashed) {
                throw new KscClientException(
                        "Failed to stash the existing credentials file " + "before applying the changes.");
            }
        }
    }

    OutputStreamWriter writer = null;
    try {
        writer = new OutputStreamWriter(new FileOutputStream(destination), StringUtils.UTF8);
        ProfilesConfigFileWriterHelper writerHelper = new ProfilesConfigFileWriterHelper(writer, modifications);

        if (inPlaceModify) {
            Scanner existingContent = new Scanner(stashLocation, StringUtils.UTF8.name());
            writerHelper.writeWithExistingContent(existingContent);
        } else {
            writerHelper.writeWithoutExistingContent();
        }

        // Make sure the output is valid and can be loaded by the loader
        new ProfilesConfigFile(destination);

        if (inPlaceModify && !stashLocation.delete()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(String.format(
                        "Successfully modified the credentials file. But failed to "
                                + "delete the stashed copy of the original file (%s).",
                        stashLocation.getAbsolutePath()));
            }
        }

    } catch (Exception e) {
        // Restore the stashed file
        if (inPlaceModify) {
            boolean restored = false;

            try {
                // We don't really care about what destination.delete()
                // returns, since the file might not have been created when
                // the error occurred.
                if (!destination.delete()) {
                    LOG.debug("Unable to remove the credentials file " + "before restoring the original one.");
                }
                restored = stashLocation.renameTo(destination);
            } finally {
                if (!restored) {
                    throw new KscClientException("Unable to restore the original credentials file. "
                            + "File content stashed in " + stashLocation.getAbsolutePath());
                }
            }
        }

        throw new KscClientException(
                "Unable to modify the credentials file. " + "(The original file has been restored.)", e);

    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.microfocus.application.automation.tools.run.JobConfigRebrander.java

private void convertXmlFileIfNotExists(@Nonnull TaskListener listener, File file, File replacedFile) {
    if (!replacedFile.exists() && file.renameTo(replacedFile)) {
        XmlFile xmlFile = new XmlFile(replacedFile);
        convertOldNameToNewName(listener, xmlFile);
    }//from   ww w  . java  2  s  . co m
}