FTP Server : Change working directory

In this tutorial you will learn how to change working directory on FTP server using java.

FTP Server : Change working directory

Change working directory on FTP Server

In this tutorial you will learn how to change working directory on FTP server using java.

Change Directory :

FTP Server provides a way to transfer files from one computer to another computer through network and internet. You must be valid user for using FTP server. Before applying any operation on FTP server first we need to connect to the server by using connect method of FTPClient class next input valid user name and password to login by calling method login("username","password");

client.connect("localhost");
result = client.login("admin", "admin");

You can change your working directory on FTP server, by using FTPClient class method which is mentioned bellow -

boolean changeWorkingDirectory(String dirName) : This method change the current working directory to the specified directory. dirName may be absolute path or relative path.
Here is example -

changeWorkingDirectory("/ftpNew") // this method changes your current working directory to the ftpNew directory under server?s root directory.

changeWorkingDirectory("ftpNew") // this method changes your current working directory to the ftpNew directory relative to the previous working directory.

Example : This example represents how to change the working directory on ftp server. Here "ftpNew " is our new directory.

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 FtpChangeDirectory {
	public static void main(String[] args) throws IOException {
		FTPClient client = new FTPClient();
		boolean result;
		try {
			// Connect to the localhost
			client.connect("localhost");

			// login to ftp server
			result = client.login("admin", "admin");
			if (result == true) {
				System.out.println("Successfully logged in!");
			} else {
				System.out.println("Login Fail!");
				return;
			}
			String newDir = "/ftpNew";

			// Changing working directory
			result = client.changeWorkingDirectory(newDir);

			if (result == true) {
				System.out.println("Working directory is changed. Your New working directory : "
								+ newDir);
			} else {
				System.out.println("Unable to change");
			}
		} catch (FTPConnectionClosedException e) {
			e.printStackTrace();
		} finally {
			try {
				client.disconnect();
			} catch (FTPConnectionClosedException e) {
				System.out.println(e);
			}
		}

	}
}

Output :

Successfully logged in!
Working directory is changed. Your New working directory : /ftpNew