FTPClient : Rename Remote File

In this tutorial, you will learn how to rename file on the server by using FTPClient class.

FTPClient : Rename Remote File

FTPClient : Rename Remote File

In this tutorial, you will learn how to rename file on the server by using FTPClient class.

Rename Remote File : Sometimes it is required to rename the file name. FTPClient class provides method to rename the existence file with the new name.

boolean rename(String oldName, String newName) : This is of boolean type and returns true if file is renamed successfully otherwise false.

This method takes two parameters -
oldName : It is remote file which we are going to rename.
newName : It is new name given to the file.

It throws FTPConnectionClosedException and IOException.

Example : In this example we are renaming "test.txt" to the new name "newFtp.txt" by using FTPClient class method rename(String oldName, String newName).

import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPFile;

class FtpRenameFile {
	public static void main(String[] args) throws IOException {
		FTPClient client = new FTPClient();
		boolean result;
		try {
			client.connect("localhost");
			result = client.login("admin", "admin");

			if (result == true) {
				System.out.println("User successfully logged in.");
			} else {
				System.out.println("Login failed!");
				return;
			}
			// Rename file.
			result = client.rename("/test.txt", "newFtp.txt");
			if (result == true) {
				System.out.println("File renamed!");
			} else {
				System.out.println("File renaming is failed.");
			}

		} catch (FTPConnectionClosedException e) {
			System.out.println(e);
		} finally {
			try {

				client.disconnect();
			} catch (FTPConnectionClosedException e) {
				System.out.println(e);
			}
		}
	}
}

Output :

User successfully logged in.
File renamed!