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
how to copy a file from one folder to another
using sftp protocol in java
We updated the article with SFTP examples, more examples in below link.
https://mkyong.com/java/file-transfer-using-sftp-in-java-jsch/
need your assistance to navigate different directory in unix using java program
How you want to navigate, try
Paths
?Now-a-days you will want to use this:
“Files.move(source, target, REPLACE_EXISTING);”
I think this will not move files between drives. Nevermind, it does for me.
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
If it involves multiple files, try
FileVisitor
https://mkyong.com/java/how-to-copy-directory-in-java/
hi i want to move files from one folder to other in sftp using java in sprigboot can you help me with that?
How we can move yesterday date file into other directory?
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.
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.
Try NIO
Files.move
, it will return the correct exception.This can be achieved thro’ JSP?If so please share the Codes
The code is
Files.move
Hi same code is not working for FTP server,
I want to move some zip files from FTP server to local drive.
Try JSch library to move files to remote server directory.
https://mkyong.com/java/file-transfer-using-sftp-in-java-jsch/
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();
The legacy
fie.renameTo
will not throw exception if operation failed. TryFiles.move
hi i used this code to move file from one directory to another in android, but it is not working
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
You cannot import it in Android.
did the same code works for android emulator?
Indeed, there’s an API to move files:
http://docs.oracle.com/javase/tutorial/essential/io/move.html
I have two files in the directory, the first one fails but the second is successful when using renameTo. Why is it like that?
Hi, thanks for the information about java in your web site! Great work!
Can you copy a File Video…Example: copy a video From C:\\ To D:\\ (OS)
hi i tried to copy an image and video files using the same code and it worked.
mkyong, god bless you @_@
Thanks very helpfull
my query is … how can i run this file movo java code in browser using javascript?
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.
Hello i am very much interested in java and it’s technologies . i found lots of new things from your blog
how to upload file to a network drive in oracle 10g?
If SSH is allowed, try JSch library, please visit the below example.
https://mkyong.com/java/file-transfer-using-sftp-in-java-jsch/
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.
Paths.get(whateverfile)
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.
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!
Try
FileVisitor
https://mkyong.com/java/how-to-delete-directory-in-java/
“renameTo” logic is good one……..
renameTo is a separate function?
“renameTo” only works if the source and destination is in the same filesystem (same drive if on pc, same storage if on mobile)
I’ve just successfully copied a file from disk D: to disc C:
perhaps ur disk C and D is separated by logical partition
and they still running on the same harddrive
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?
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();
}
}
}
]]
43434
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.
Only one line
Files.move(Path source, Path target)
.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?
Do you have read permission for the src folder, and write permission for the target folder?
Its just two lines. The file name and new file name. Everything else is just class setup and fail-safes