The File Transfer Protocol (FTP) is a standard network protocol used to transfer computer files between a client and server on a computer network. The example below shows you how to connect to an FTP server.
In this example we are using the FTPClient
class of the Apache Commons Net library. To connect to the server, we need to provide the FTP server name. Login to the server can be done by calling the login()
method of this class with a valid username
and password
. To logout we call the logout()
method.
Let’s try the code snippet below:
package org.kodejava.commons.net;
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
public class FTPConnectDemo {
public static void main(String[] args) {
FTPClient client = new FTPClient();
try {
client.connect("ftp.example.com");
// When login success, the login method returns true.
boolean login = client.login("demo", "password");
if (login) {
System.out.println("Login success...");
// When logout success, the logout method returns true.
boolean logout = client.logout();
if (logout) {
System.out.println("Logout from FTP server...");
}
} else {
System.out.println("Login fail...");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Closes the connection to the FTP server
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Maven Dependencies
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.10.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
How do I do
FTPClient.connect()
with a IP address?You can simply use the textual representation of the IP address as the argument to the connect method. For example
FTPClient.connect("127.0.0.1")
. Or you can create anInetAddress
object usingInetAddress.getByName("127.0.0.1")
and then pass thisInetAddress
as the argument to the connect method.