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.sun.portal.portletcontainer.driver.admin.UploadServlet.java

private String processFileItem(FileItem fi) throws FileUploadException {

    // On some browsers fi.getName() will return the full path to the file
    // the client select this can cause problems
    // so the following is a workaround.
    try {/*  w  w w .  j  ava 2 s .  co  m*/
        String fileName = fi.getName();
        if (fileName == null || fileName.trim().length() == 0) {
            return null;
        }
        fileName = FilenameUtils.getName(fileName);

        File fNew = File.createTempFile("opc", ".tmp");
        fNew.deleteOnExit();
        fi.write(fNew);

        File finalFileName = new File(fNew.getParent() + File.separator + fileName);
        if (fNew.renameTo(finalFileName)) {
            return finalFileName.getAbsolutePath();
        } else {
            // unable to rename, copy the contents of the file instead
            PortletWarUpdaterUtil.copyFile(fNew, finalFileName, true, false);
            return finalFileName.getAbsolutePath();
        }

    } catch (Exception e) {
        throw new FileUploadException(e.getMessage());
    }
}

From source file:com.att.aro.core.fileio.impl.FileManagerImpl.java

/**
 * rename a File with a newName//from w w  w  . j  a  v  a  2 s  .c o m
 * 
 * @param origFileName
 *            a File
 * @param newName
 *            a String containing a new name
 * @return
 */
@Override
public boolean renameFile(File origFileName, String newName) {
    String path = origFileName.getParent();
    File renameFile = createFile(path, newName);

    return (!renameFile.exists() && origFileName.renameTo(renameFile));
}

From source file:com.owncloud.android.operations.RenameFileOperation.java

private void saveLocalFile() {
    mFile.setFileName(mNewName);//from   w  ww.  j  a  v a 2 s. c  o  m

    // try to rename the local copy of the file
    if (mFile.isDown()) {
        File f = new File(mFile.getStoragePath());
        String parentStoragePath = f.getParent();
        if (!parentStoragePath.endsWith(File.separator))
            parentStoragePath += File.separator;
        if (f.renameTo(new File(parentStoragePath + mNewName))) {
            mFile.setStoragePath(parentStoragePath + mNewName);
        }
        // else - NOTHING: the link to the local file is kept although the local name can't be updated
        // TODO - study conditions when this could be a problem
    }

    mStorageManager.saveFile(mFile);
}

From source file:net.stickycode.deploy.grizzly.WarTest.java

private void writeToFile(HttpEntity entity, File file) throws IOException {
    File tmp = File.createTempFile("sticky", ".part");
    log.info("tmp file {}", tmp);
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tmp));
    try {//w  w  w .j  a  v a 2 s  .co m
        entity.writeTo(out);
    } finally {
        out.close();
        log.info("copy {} to {}", tmp, file);
        file.getParentFile().mkdirs();
        if (!tmp.renameTo(file))
            throw new RuntimeException("failed to download " + file);
    }

}

From source file:com.dycody.android.idealnote.async.upgrade.UpgradeProcessor.java

/**
 * Upgrades all the old audio attachments to the new format 3gpp to avoid to exchange them for videos
 *//*from  www  .ja  va  2s  .c  o  m*/
private void onUpgradeTo480() {
    final DbHelper dbHelper = DbHelper.getInstance();
    for (Attachment attachment : dbHelper.getAllAttachments()) {
        if ("audio/3gp".equals(attachment.getMime_type()) || "audio/3gpp".equals(attachment.getMime_type())) {

            // File renaming
            File from = new File(attachment.getUriPath());
            FilenameUtils.getExtension(from.getName());
            File to = new File(from.getParent(), from.getName()
                    .replace(FilenameUtils.getExtension(from.getName()), Constants.MIME_TYPE_AUDIO_EXT));
            from.renameTo(to);

            // Note's attachment update
            attachment.setUri(Uri.fromFile(to));
            attachment.setMime_type(Constants.MIME_TYPE_AUDIO);
            dbHelper.updateAttachment(attachment);
        }
    }
}

From source file:com.esofthead.mycollab.vaadin.ui.AttachmentPanel.java

public List<File> files() {
    List<File> listFile = null;
    if (MapUtils.isNotEmpty(fileStores)) {
        listFile = new ArrayList<>();
        for (String fileName : fileStores.keySet()) {
            File oldFile = fileStores.get(fileName);
            File parentFile = oldFile.getParentFile();
            File newFile = new File(parentFile, fileName);
            if (newFile.exists())
                newFile.delete();//from   w  ww . ja  v a2 s .  c o  m
            if (oldFile.renameTo(newFile)) {
                listFile.add(newFile);
            }

            if (listFile.size() <= 0)
                return null;

        }
    }
    return listFile;
}

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

/**
 * Download file with urlConnection/* w  w w . j a  v  a 2 s.  c  om*/
 * @author : BangHN
 * since : 1.0
 */
public static void downloadWithURLConnection(String url, File output, File tmpDir) {
    BufferedOutputStream os = null;
    BufferedInputStream is = null;
    File tmp = null;
    try {
        VTLog.i("Download ZIPFile", "Downloading url :" + url);

        tmp = File.createTempFile("download", ".tmp", tmpDir);
        URL urlDownload = new URL(url);
        URLConnection cn = urlDownload.openConnection();
        cn.addRequestProperty("session", HTTPClient.sessionID);
        cn.setConnectTimeout(CONNECT_TIMEOUT);
        cn.setReadTimeout(READ_TIMEOUT);
        cn.connect();
        is = new BufferedInputStream(cn.getInputStream());
        os = new BufferedOutputStream(new FileOutputStream(tmp));
        //cp nht dung lng tp tin request
        fileSize = cn.getContentLength();
        //vn c tr?ng hp khng c ContentLength
        if (fileSize < 0) {
            //mc nh = 4 MB
            fileSize = 4 * 1024 * 1024;
        }
        copyStream(is, os);
        tmp.renameTo(output);
        tmp = null;
    } catch (IOException e) {
        ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false,
                TabletActionLogDTO.LOG_EXCEPTION);
        VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e));
        throw new RuntimeException(e);
    } catch (Exception e) {
        VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e));
        ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false,
                TabletActionLogDTO.LOG_EXCEPTION);
        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.sourceforge.jweb.maven.mojo.InWarMinifyMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled)
        return;//w ww.ja v  a  2  s . co m
    processConfiguration();
    String name = this.getBuilddir().getAbsolutePath() + File.separator + this.getFinalName() + "."
            + this.getPacking();
    this.getLog().info(name);
    MinifyFileFilter fileFilter = new MinifyFileFilter();
    int counter = 0;
    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            //no compress, just transfer to war
            if (!fileFilter.accept(entry)) {
                getLog().debug("nocompress entry: " + entry.getName());
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }

            File sourceTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".tmp");
            File destTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".min.tmp");
            FileUtils.writeStringToFile(sourceTmp, "");
            FileUtils.writeStringToFile(destTmp, "");

            //assemble arguments
            String[] provied = getYuiArguments();
            int length = (provied == null ? 0 : provied.length);
            length += 5;
            int i = 0;

            String[] ret = new String[length];

            ret[i++] = "--type";
            ret[i++] = (entry.getName().toLowerCase().endsWith(".css") ? "css" : "js");

            if (provied != null) {
                for (String s : provied) {
                    ret[i++] = s;
                }
            }

            ret[i++] = sourceTmp.getAbsolutePath();
            ret[i++] = "-o";
            ret[i++] = destTmp.getAbsolutePath();

            try {
                InputStream in = zipFile.getInputStream(entry);
                FileUtils.copyInputStreamToFile(in, sourceTmp);
                in.close();

                YUICompressorNoExit.main(ret);
            } catch (Exception e) {
                this.getLog().warn("compress error, this file will not be compressed:" + buildStack(e));
                FileUtils.copyFile(sourceTmp, destTmp);
            }

            out.putNextEntry(new ZipEntry(entry.getName()));
            InputStream compressedIn = new FileInputStream(destTmp);
            byte[] buf = new byte[512];
            int len = -1;
            while ((len = compressedIn.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            compressedIn.close();

            String sourceSize = decimalFormat.format(sourceTmp.length() * 1.0d / 1024) + " KB";
            String destSize = decimalFormat.format(destTmp.length() * 1.0d / 1024) + " KB";
            getLog().info("compressed entry:" + entry.getName() + " [" + sourceSize + " ->" + destSize + "/"
                    + numberFormat.format(1 - destTmp.length() * 1.0d / sourceTmp.length()) + "]");

            counter++;
        }
        zipFile.close();
        out.close();

        FileUtils.cleanDirectory(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
        FileUtils.forceDelete(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.castlemock.web.basis.manager.FileManager.java

/**
 * The method provides the functionality to rename a directory from one name to another.
 * @param oldFolderPath The path to the directory that should receive the new name. Note that the path contains
 *                      the old directory name.
 * @param newFolderPath The new path to the directory that should be renamed. Note that the path contains
 *                      the new directory name.
 * @return Returns the result of the rename operation.
 *//* ww w.j a  v a 2 s  .c o  m*/
public boolean renameDirectory(final String oldFolderPath, final String newFolderPath) {
    File oldFileDirectory = new File(oldFolderPath);
    if (!oldFileDirectory.exists() || !oldFileDirectory.isDirectory()) {
        // The directory was not found and therefore no rename operation was accomplished.
        return false;
    }

    File newFileDirectory = new File(newFolderPath);
    return oldFileDirectory.renameTo(newFileDirectory);
}

From source file:org.nekorp.workflow.desktop.data.access.rest.ImagenDAOImp.java

@Override
public ImagenMetadata saveImage(BufferedImage image) {
    try {//from  ww  w. j  a  v a  2 s. c om
        ImagenMetadata r = factory.getTemplate().getForObject(factory.getRootUlr() + "/upload/url",
                ImagenMetadata.class);
        File file = new File("data/upload.jpg");
        ImageIO.write(image, "jpg", file);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("myFile", new FileSystemResource(file));
        r = factory.getTemplate().postForObject(r.getUploadUrl(), form, ImagenMetadata.class);
        File cache = new File("data/" + r.getRawBlobKey());
        file.renameTo(cache);
        return r;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}