Change working directory on FTP Server

 

FTPClient class provides method to replace the parent directory.

boolean changeToParentDirectory() : Working of this method is to replace the parent directory of the present working directory. It is of boolean type. Returns true if method completed properly otherwise returns false.

It throws FTPConnectionClosedException and IOException.
 
** UPDATE: FTP Complete tutorial now available here.
 
Example :

This example contains code to change the current working directory using client.changeWorkingDirectory(newDir) and change the parent directory using method client.changeToParentDirectory().

Here is program to demonstrate├é┬á –

 
File : FtpChangeParentDir.java
 


package com.simplecode.net;

import java.io.IOException;

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

class FtpChangeParentDir {
public static void main(String[] args) throws IOException {

FTPClient ftpClient = new FTPClient();
boolean result;
try {
	// Connect to the localhost
	ftpClient.connect("localhost");

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

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

	if (result == true) {
   System.out.println("Working directory is changed.Your New working directory:"+newDir);
	} else {
		System.out.println("Unable to change");
	}
	result = ftpClient.changeToParentDirectory();
	if (result == true) {
		System.out.println("Parent directory is changed");
	} else {
		System.out.println("Unable to change Parent directory");
		}
	} 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.