Java File Move nui moveFile(String sourceFile, String destFile)

Here you can find the source of moveFile(String sourceFile, String destFile)

Description

Moves a file.

License

Open Source License

Parameter

Parameter Description
sourceFile a parameter
destFile a parameter

Return

true if successful, false otherwise.

Declaration

public static boolean moveFile(String sourceFile, String destFile) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class Main {
    /**/*from   w  ww . ja  v  a  2s  .  co  m*/
     * Moves a file.
     * @param sourceFile
     * @param destFile
     * @return true if successful, false otherwise.
     */
    public static boolean moveFile(String sourceFile, String destFile) {
        java.io.File source = new java.io.File(sourceFile);
        java.io.File dest = new java.io.File(destFile);
        try {
            copyFile(source, dest);
            source.delete();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Copies a file
     * @param sourceFile
     * @param destFile
     * @return true if successful, false otherwise.
     */
    public static boolean copyFile(String sourceFile, String destFile) {
        java.io.File source = new java.io.File(sourceFile);
        java.io.File dest = new java.io.File(destFile);
        try {
            copyFile(source, dest);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Copies a file via java.io.FileUtils types.
     * @param sourceFile
     * @param destFile
     * @throws IOException
     */
    public static void copyFile(java.io.File sourceFile, java.io.File destFile) throws IOException {
        if (!destFile.exists()) {
            destFile.createNewFile();
        }

        FileChannel source = null;
        FileChannel destination = null;

        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }
}

Related

  1. moveFile(File from, File to)
  2. moveFile(File source, File destination)
  3. moveFile(File src, File dest)
  4. moveFile(final File srcFile, final File destFile)
  5. moveFile(String source, String target)
  6. moveFiles(File src, String newSrc, File dest)
  7. mover(String file, String caminhoNovo)