[java] How do I move a file from one location to another in Java?

How do you move a file from one location to another? When I run my program any file created in that location automatically moves to the specified location. How do I know which file is moved?

This question is related to java file move

The answer is


Files.move(source, target, REPLACE_EXISTING);

You can use the Files object

Read more about Files


Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.

// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
    File tDir = new File(targetPath);
    if (tDir.exists()) {
        String newFilePath = targetPath+File.separator+sourceFile.getName();
        File movedFile = new File(newFilePath);
        if (movedFile.exists())
            movedFile.delete();
        return sourceFile.renameTo(new File(newFilePath));
    } else {
        LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
        return false;
    }       
}

Java 6

public boolean moveFile(String sourcePath, String targetPath) {

    File fileToMove = new File(sourcePath);

    return fileToMove.renameTo(new File(targetPath));
}

Java 7 (Using NIO)

public boolean moveFile(String sourcePath, String targetPath) {

    boolean fileMoved = true;

    try {

        Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);

    } catch (Exception e) {

        fileMoved = false;
        e.printStackTrace();
    }

    return fileMoved;
}

You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:

  1. read the source file into memory
  2. write the content to a file at the new location
  3. delete the source file

File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.


Just add the source and destination folder paths.

It will move all the files and folder from source folder to destination folder.

    File destinationFolder = new File("");
    File sourceFolder = new File("");

    if (!destinationFolder.exists())
    {
        destinationFolder.mkdirs();
    }

    // Check weather source exists and it is folder.
    if (sourceFolder.exists() && sourceFolder.isDirectory())
    {
        // Get list of the files and iterate over them
        File[] listOfFiles = sourceFolder.listFiles();

        if (listOfFiles != null)
        {
            for (File child : listOfFiles )
            {
                // Move files to destination folder
                child.renameTo(new File(destinationFolder + "\\" + child.getName()));
            }

            // Add if you want to delete the source folder 
            sourceFolder.delete();
        }
    }
    else
    {
        System.out.println(sourceFolder + "  Folder does not exists");
    }

With Java 7 or newer you can use Files.move(from, to, CopyOption... options).

E.g.

Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);

See the Files documentation for more details


To move a file you could also use Jakarta Commons IOs FileUtils.moveFile

On error it throws an IOException, so when no exception is thrown you know that that the file was moved.


File.renameTo from Java IO can be used to move a file in Java. Also see this SO question.


Please try this.

 private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
            boolean ismove = false;
            InputStream inStream = null;
            OutputStream outStream = null;

            try {

                File afile = new File(sourcefolder + filename);
                File bfile = new File(destinationfolder + filename);

                inStream = new FileInputStream(afile);
                outStream = new FileOutputStream(bfile);

                byte[] buffer = new byte[1024 * 4];

                int length;
                // copy the file content in bytes
                while ((length = inStream.read(buffer)) > 0) {

                outStream.write(buffer, 0, length);

                }


                // delete the original file
                afile.delete();
                ismove = true;
                System.out.println("File is copied successful!");

            } catch (IOException e) {
                e.printStackTrace();
            }finally{
               inStream.close();
               outStream.close();
            }
            return ismove;
            }

You can try this.. clean solution

Files.move(source, target, REPLACE_EXISTING);

Try this :-

  boolean success = file.renameTo(new File(Destdir, file.getName()));

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to move

Gradle - Move a folder from ABC to XYZ Moving all files from one directory to another using Python Move column by name to front of table in pandas PHP - Move a file into a different folder on the server How to move table from one tablespace to another in oracle 11g Batch file to move files to another directory Windows batch script to move files How to move files using FTP commands Moveable/draggable <div> How to move a marker in Google Maps API