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 want to move files from one folder to other in sftp using java in sprigboot can you help me with that?

    Reply
  2. How we can move yesterday date file into other directory?

    Reply
  3. Hi mkyong,
    I want to copy a file from one folder to another, and the same file need to move to another folder. Please guide.

    Reply
  4. 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.

    Reply
    1. Try NIO Files.move, it will return the correct exception.

      Reply
  5. 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.

    Reply
    1. Its just two lines. The file name and new file name. Everything else is just class setup and fail-safes

      Reply
    2. Only one line Files.move(Path source, Path target).

      Reply
      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?

        Reply
        1. Do you have read permission for the src folder, and write permission for the target folder?

          Reply
  6. how to copy a file from one folder to another
    using sftp protocol in java

    Reply
  7. need your assistance to navigate different directory in unix using java program

    Reply
  8. 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?

    Reply
  9. This can be achieved thro’ JSP?If so please share the Codes

    Reply
  10. Hi same code is not working for FTP server,
    I want to move some zip files from FTP server to local drive.

    Reply
  11. 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();
    }
    }
    }

    ]]

    Reply
  12. Now-a-days you will want to use this:

    “Files.move(source, target, REPLACE_EXISTING);”

    Reply
  13. 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();

    Reply
    1. The legacy fie.renameTo will not throw exception if operation failed. Try Files.move

      Reply
  14. hi i used this code to move file from one directory to another in android, but it is not working

    Reply
  15. 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

    Reply
  16. I have two files in the directory, the first one fails but the second is successful when using renameTo. Why is it like that?

    Reply
  17. Can you copy a File Video…Example: copy a video From C:\\ To D:\\ (OS)

    Reply
    1. hi i tried to copy an image and video files using the same code and it worked.

      Reply
  18. 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

    Reply
  19. my query is … how can i run this file movo java code in browser using javascript?

    Reply
    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.

      Reply
  20. Hello i am very much interested in java and it’s technologies . i found lots of new things from your blog

    Reply
  21. hello sir
    it’s to move a text file.
    How can i move a file other than .txt ?
    like .RAR , or any video/audio file.

    Reply
  22. 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.

    Reply
  23. 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!

    Reply
  24. “renameTo” logic is good one……..

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

        Reply
          1. perhaps ur disk C and D is separated by logical partition
            and they still running on the same harddrive

Leave a Comment

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