How to move file to another directory in Java

This article shows how to move a file to another directory in the same file drive or remote server.

  • Files.move – Move file in local system.
  • JSch – Move file to remove server (SFTP)

1. Move file to another directory

This Java example uses NIO Files.move to move a file from to another directory in the same local drive.

FileMove.java

package com.mkyong.io.file;

import java.io.IOException;
import java.nio.file.*;

public class FileMove {

    public static void main(String[] args) {

        String fromFile = "/home/mkyong/data/db.debug.conf";
        String toFile = "/home/mkyong/data/deploy/db.conf";

        Path source = Paths.get(fromFile);
        Path target = Paths.get(toFile);

        try {

            // rename or move a file to other path
            // if target exists, throws FileAlreadyExistsException
            Files.move(source, target);

            // if target exists, replace it.
            // Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);

            // multiple CopyOption
            /*CopyOption[] options = { StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES,
                                LinkOption.NOFOLLOW_LINKS };

            Files.move(source, target, options);*/

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

More Java file move examples.

2. Move file to remote server directory

This Java example uses JSch library to move a file from the local system to another directory in a remote server, using SFTP.

P.S Assume the remote server is enabled SSH login (default port 22) using a password.

pom.xml

  <dependency>
      <groupId>com.jcraft</groupId>
      <artifactId>jsch</artifactId>
      <version>0.1.55</version>
  </dependency>
SFTPFileTransfer.java

package com.mkyong.io.howto;

import com.jcraft.jsch.*;

public class SFTPFileTransfer {

    private static final String REMOTE_HOST = "1.2.3.4";
    private static final String USERNAME = "";
    private static final String PASSWORD = "";
    private static final int REMOTE_PORT = 22;
    private static final int SESSION_TIMEOUT = 10000;
    private static final int CHANNEL_TIMEOUT = 5000;

    public static void main(String[] args) {

        // local
        String localFile = "/home/mkyong/hello.sh";

        // remote server
        String remoteFile = "/home/mkyong/test.sh";

        Session jschSession = null;

        try {

            JSch jsch = new JSch();
            jsch.setKnownHosts("/home/mkyong/.ssh/known_hosts");
            jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);

            // authenticate using private key
            // jsch.addIdentity("/home/mkyong/.ssh/id_rsa");

            // authenticate using password
            jschSession.setPassword(PASSWORD);

            // 10 seconds session timeout
            jschSession.connect(SESSION_TIMEOUT);

            Channel sftp = jschSession.openChannel("sftp");

            // 5 seconds timeout
            sftp.connect(CHANNEL_TIMEOUT);

            ChannelSftp channelSftp = (ChannelSftp) sftp;

            // transfer file from local to remote server
            channelSftp.put(localFile, remoteFile);

            // download file from remote server to local
            // channelSftp.get(remoteFile, localFile);

            channelSftp.exit();

        } catch (JSchException | SftpException e) {

            e.printStackTrace();

        } finally {
            if (jschSession != null) {
                jschSession.disconnect();
            }
        }

    }

}

Please visit this file Transfer using SFTP in Java (JSch).

Note
The NIO Files.move can’t move a file from the local system to a remote server directory.

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-io

References

53 comments on “How to move file to another directory in Java

  1. Hi,I use the same code but when I used the first code It told me “File is failed to move”,when I used the second code it was saying “java.io.FileNotFoundException”, was it due to a mismatch between wins and java character rules?
    Anyway,thank you for your answer.

  2. 15 lines just to move a file from a folder to another folder !!!

    I’m exhausted just by looking at the code…

    I can’t understand what was in Sun engineers mind when they created that spaghetti dish of a language.

      1. This command is only copying file name, its is not copying the content. File copied in the target folder is of 0kb. What could be the issue?

  3. Dear Mkyong,

    Whether “C:\folderA\Afile.txt” can be saved in String named text and this text can be called in File like

    File afile =new File(text);
    this is possible?

  4. i used this

    [[

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package copy;

    /**
    *
    * @author Dev1
    */
    import java.io.File;
    public class Copy {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
    try{
    File afile =new File(“C:\9.txt”);

    if(afile.renameTo(new File(“C:\hi\9.txt” + afile.getName()))){
    System.out.println(“File is moved successful!”);
    }else{
    System.out.println(“File is failed to move!”);
    }

    }catch(Exception e){
    e.printStackTrace();
    }
    }
    }

    ]]

  5. my code is this

    File wallpaperDirectory3 = new File(“/sdcard/Download/Scan1.jpg”);

    boolean success = wallpaperDirectory3.renameTo(new File(

    wallpaperDirectory, wallpaperDirectory3.getName()));

    Toast.makeText(getApplicationContext(), “” + success, Toast.LENGTH_LONG)

    .show();

  6. why not using “java.nio.file.StandardCopyOption” ?

    well I’m looking for easy and effective way for moving whole folder to other location(can be on different filesystem or the same one) and found the “Files.move()” method from the Java documentation

  7. Hi mkyong

    i have files few files in dir Screenshots i want to create new Dir in screenshots and move all files to that dir . how we can achieve this

    Thanks in advance

    ArunKongara

    1. Run Java code in browser using JavaScript!? I’m not sure what is your use case, it is better rewrite the Java code in JavaScript.

  8. Good exercise. In the copy & delete example, it would be good to use “deleteOnExit()”. If we use “delete()” the source file might be still in use and may not get deleted.

    Thanks.

  9. Thanks for this tutorial. I gave this a shot such that I am calling it in a loop and iterating over serveral files in a directory to be moved to a new location. It did the move of all the files perfectly. However, only one file was actually deleted. Is there something that must be added in order to get it to delete the files in the source directly with successive calls to this function? Your thought would be much appreciated.

    Cheers!

      1. “renameTo” only works if the source and destination is in the same filesystem (same drive if on pc, same storage if on mobile)

Leave a Comment

Your email address will not be published. Required fields are marked *