Create Directory on FTP Server
In this section you will learn how to create directory on FTP server using java.
Create Directory :
By using FTP Server we can 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 create new directory on FTP server ,by using FTPClient class method which is mentioned bellow -
boolean makeDirectory(String name) : This method
creates new directory on your FTP server. name is your mentioned name of
directory.It may be relative as well as absolute.
Here is example :
ftpClient.makeDirectory("ftpNew") ; // relative path. It will create directory "ftpNew" in the current directory
ftpClient.makeDirectory("ftpNew") ; //absolute path. It will create directory "ftpNew" under server?s root directory.
Example : In this example we are creating new directory in ftp server.
import java.io.IOException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPConnectionClosedException; class FtpCreateDirectory{ 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("Successfully logged in!"); } else { System.out.println("Login Fail!"); return; } //Changing the working directory result=ftpClient.changeWorkingDirectory("/ftpNew"); if(result==true){ System.out.println("New Directory is created on Ftp Server!"); } else{ System.out.println("Unable to create new directory!"); } } catch (FTPConnectionClosedException e) { e.printStackTrace(); } finally { try { ftpClient.disconnect(); } catch (FTPConnectionClosedException e) { System.out.println(e); } } } }
Output :
Successfully logged in! New Directory is created on Ftp Server!