Pages Navigation Menu

Coding is much easier than you think

Rename file on the FTP server

Rename file on the FTP server

 

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 else false.

This method takes 2 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.
 
** UPDATE: FTP Complete tutorial now available here.
 
Demo : File : FtpFileRename.java

package com.simplecode.com;

import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;

class FtpFileRename {
	public static void main(String[] arg) throws IOException {
		FTPClient ftpClient = new FTPClient();
		boolean result;
		try {
			// Connect to the localhost
			ftpClient.connect("localhost");

			// login to ftp server
			result = ftpClient.login("admin", "password");

			if (result == true) 
                        {
				System.out.println("Logged in Successfully !");
			} 
                        else 
                        {
				System.out.println("Login Fail !");
				return;
			}
			// Rename file.
			result = ftpClient.rename("/oldFile.pdf", "newFile.pdf");
			if (result == true)
                        {
				System.out.println("File renamed !");
			} 
                        else
                        {
				System.out.println("File renaming failed ");
			}

		} 
                catch (FTPConnectionClosedException e) 
                {
			System.err.println(e);
		}
                finally 
                {
			try 
                        {
			ftpClient.disconnect();
			}
                        catch (FTPConnectionClosedException e) 
                        {
				System.err.println(e);
			}
		}
	}
}

 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.