Java IO Tutorial

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
53 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
nagar
6 years ago

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

gnanavelu
6 years ago

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

Guest
9 years ago

Now-a-days you will want to use this:

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

hikingmike
8 years ago
Reply to  Guest

I think this will not move files between drives. Nevermind, it does for me.

ArunKongara
10 years ago

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

Vrushabh Dhond
1 year ago

hi i want to move files from one folder to other in sftp using java in sprigboot can you help me with that?

Abhishek Keshri
2 years ago

How we can move yesterday date file into other directory?

gautam
3 years ago

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.

humukou
5 years ago

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.

revathi muthu krishnan
8 years ago

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

Goms
9 years ago

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

Aamir Ali
9 years ago

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();

Aamir Ali
9 years ago

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

visitor
9 years ago

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

wffger
9 years ago
Reply to  visitor

You cannot import it in Android.

vyshu
9 years ago

did the same code works for android emulator?

Stefan Dietiker
10 years ago

Indeed, there’s an API to move files:

http://docs.oracle.com/javase/tutorial/essential/io/move.html

jo
10 years ago

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

Alket
10 years ago

Hi, thanks for the information about java in your web site! Great work!

Mr.Help
10 years ago

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

Mwesigye John Bosco
10 years ago
Reply to  Mr.Help

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

Aufar Sukmajaya
10 years ago

mkyong, god bless you @_@

Ravinath
10 years ago

Thanks very helpfull

Jay Joshi
11 years ago

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

Jay Joshi
11 years ago

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

Jesslyn
11 years ago

how to upload file to a network drive in oracle 10g?

akhil kumar
11 years ago

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.

Ananth
11 years ago

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.

missserena
11 years ago

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!

pradip garala
11 years ago

“renameTo” logic is good one……..

mmmm
11 years ago
Reply to  pradip garala

renameTo is a separate function?

visitor
9 years ago
Reply to  mmmm

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

sers
8 years ago
Reply to  visitor

I’ve just successfully copied a file from disk D: to disc C:

Jun Jie Gan
8 years ago
Reply to  sers

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

revathi muthu krishnan
8 years ago

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?

bial
9 years ago

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

]]

kk
9 years ago
Reply to  bial

43434

stephanep
6 years ago

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.

Richa
2 years ago
Reply to  mkyong

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?

Keith
5 years ago
Reply to  stephanep

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