The FTPClient class in Apache Commons Net API provides a convenient method to rename a remote file/directory on a FTP server. Syntax of this method look like:
boolean rename(String from, String to) throws IOException
Where:
Here are some examples on usage of this method:
ftpClient.rename("photo", "photo_2012");
ftpClient.rename("Puppy.jpg", "Puppy_Old.jpg");
ftpClient.rename("/personal/photo", "/personal/photo_2012");
ftpClient.rename("/personal/photo/Puppy.jpg", "/personal/photo/Puppy_Old.jpg");
ftpClient.rename("/personal/photo/family/2012", "/personal/photo/wedding/2012");
NOTE: It’s recommended to check result of the rename() method to make sure the operation is actually successful or not. For example:
boolean success = ftpClient.rename("photo", "photo_2012"); if (success) { // rename succeeded } else { // rename failed }
The following small program demonstrates how to connect to a FTP server to rename a file and a directory, and disconnect:
package net.codejava.ftp; import java.io.IOException; import org.apache.commons.net.ftp.FTPClient; public class FTPRenamer { public static void main(String[] args) { String server = "www.ftpserver.com"; int port = 21; String user = "username"; String pass = "password"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(user, pass); // renaming directory String oldDir = "/photo"; String newDir = "/photo_2012"; boolean success = ftpClient.rename(oldDir, newDir); if (success) { System.out.println(oldDir + " was successfully renamed to: " + newDir); } else { System.out.println("Failed to rename: " + oldDir); } // renaming file String oldFile = "/work/error.png"; String newFile = "/work/screenshot.png"; success = ftpClient.rename(oldFile, newFile); if (success) { System.out.println(oldFile + " was successfully renamed to: " + newFile); } else { System.out.println("Failed to rename: " + oldFile); } ftpClient.logout(); ftpClient.disconnect(); } catch (IOException ex) { ex.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.logout(); ftpClient.disconnect(); } catch (IOException ex) { ex.printStackTrace(); } } } } }
Remember to update the variable server, port, userand pass according to your FTP account setting.