Upload file on ftp server using java

In this tutorial, we will see how to upload file on ftp server using java. To upload file on ftp sever using java, we can use the Apache Commons Net library.

Code to upload file on ftp server using java:-
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

public class FTPFileUpload {

    public static void main(String... args) {

        String server = "";
        int port = 21;
        String username = "your_username";
        String password = "your_password";
        String remoteFilePath = "/ftp";
        String localFilePath = "c:\\test.txt";

        FTPClient ftpClient = new FTPClient();
        ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

        try {

            ftpClient.connect(server, port);
            ftpClient.login(username, password);

            if (!ftpClient.changeWorkingDirectory(remoteFilePath)) {
                System.out.println("Remote directory does not exist.");

            File localFile = new File(localFilePath);
            FileInputStream inputStream = new FileInputStream(localFile);

            boolean uploadFile = ftpClient.storeFile(localFile.getName(), inputStream);

            if (uploadFile) {
                System.out.println("File uploaded successfully.");
            } else {
                System.out.println("File upload failed.");

        } catch (IOException e) {
        } finally {
            try {
            } catch (IOException ex) {

The provided Java code is an example of how to use the Apache Commons Net library to upload a file to an FTP server. It demonstrates how to connect to an FTP server, log in, navigate to a specific directory on the server, and upload a file.

Let’s break down the code step by step:

1. An instance of FTPClient is created to manage the FTP connection.

2. A command listener is added to the FTPClient to print the FTP commands and server responses to the   console for debugging purposes.

3. ftpClient.enterLocalPassiveMode() enables passive mode for the FTP connection.

4. ftpClient.setFileType(FTP.BINARY_FILE_TYPE) sets the file transfer type to binary mode.

5. ftpClient.changeWorkingDirectory(remoteFilePath) checks if the remote directory specified by remoteFilePath exists on the server. If the directory does not exist, it prints a message and returns.

6. It creates a File object for the local file specified by localFilePath.

7. Opens an FileInputStream to read the local file.

8. Uploads the file to the FTP server using ftpClient.storeFile(localFile.getName(), inputStream). It stores the file with the same name as the local file.

9. After the upload is complete, it checks the return value of ftpClient.storeFile(). If true, it prints “File uploaded successfully.” If false, it prints “File upload failed.”

10. The code includes exception handling for potential IOExceptions that can occur during FTP operations.

11. In the finally block, the code logs out from the FTP server using ftpClient.logout() and disconnects from the server using ftpClient.disconnect().

This code provides a basic example of how to upload file on FTP server using Apache Commons Net.

You should replace the placeholder values for server, username, password, remoteFilePath, and localFilePath with your actual FTP server details and the file you want to upload.

Source Code:- Download source code

inner classes in java

in this post we will discuss about the inner classes in java. so what is inner class and when we should go for inner classes. Sometimes when we declare a class inside another class, such type of class is called inner class. class Car { System.out.println(“inside car class”); class Engine{ System.out.println(“inside engine inner class”); } … Read more

implement selection sort algorithm in java

In this tutorial we will see that how to implement selection sort algorithm in java. The selection sort is a combination of searching and sorting. During each pass, the unsorted element with the smallest or largest value is moved to its proper position in the array. The number of times the sort passes through the … Read more

User defined exception in java

User defined exception in java can be created by extending any predefined exception. User defined exception in java are also called Custom Exceptions. In java if we are developing an application and get some requirement to instruct the user who is going to use our class about the problem occurred while executing the statement. To … Read more

Connection Pooling in JDBC using Apache Commons DBCP

In this Example We will implement the connection pooling in JDBC using Apache Commons DBCP. Now what is Connection Pool? Connection Pool is a cache of database connections so that connection can be reused when future requests to the database are required. Opening a database connection for each user is a wastage of resource and … Read more

Enum Types in Java

Enum was introduced in java 5. Enum types in java is a special type of class to define collection of constants. Variables in enum are constants so there name should be in uppercase letters. In java we define an enum type by using the enum keyword. Enum types in java is used to represent a … Read more

Bubble Sort in Java

Bubble Sort in Java in a bubble sorting algorithm, in which elements of the list gradually rise or bubble to their proper location in the array. Bubble sort algorithms cycle through a list, analyzing pairs of elements from left to right, or beginning to end. If the leftmost element in the pair is less than … Read more

Split String in Java

There are different ways to Split the String in Java, out of which some common ways are shown to Split String in Java. Here in this Example We will Split the String using the String Split Method public class SplitString { public static void main(String[] args){ String str = “java-language”; String[] parts = str.split(“-“); String … Read more

List All Column Names of Table using Java

We can list all column names of table using java.sql.DatabaseMetaData.getColumns() method. The getColumn method accepts String catalog, String schemaPattern, String tableNamePattern and String columnNamePattern parametres. It retrieves a description of table columns available in the specified catalog. The method return ResultSet where each row is a column description. Example to list all column names of … Read more

List All Table Names of Database using Java

We can list all table names of database using java.sql.DatabaseMetaData.getTables() method. The getTables method accepts catalog, schemaPattern, tablenamePattern, types parameters and returns ResultSet where each row is table description. Each table descriptor contain the following columns: String TABLE_CAT represents table catalog and can be null String TABLE_SCHEM represents table schema and can be null String … Read more