# Upload a file using FTP in Java (with example)

In 
FTP
Published 2022-12-03

This article will explain to you how to upload a file using FTP in Java. This tutorial will show you an example as well.

Sometimes you need to create a Java FTP client to upload a file to a FTP server.

Here it is an example:

package ftp.upload.java;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

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

public class FtpUploadJavaExample {

  public static void main(String[] args) {

    FTPClient ftpClient = new FTPClient();

    try {

      ftpClient.connect("192.168.6.130", 21);
      ftpClient.login("oracle", "1");
      ftpClient.enterLocalPassiveMode();

      ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

      File LocalFile = new File("C:/JAVA/EJBClient.jar");

      String remoteFile = "/u01/dir1/EJBClient.jar";
      InputStream inputStream = new FileInputStream(LocalFile);

      System.out.println("Start uploading first file");
      boolean done = ftpClient.storeFile(remoteFile, inputStream);
      inputStream.close();

      if (done) {
        System.out.println("The first file is uploaded using FTP successfully.");
      }

    } catch (IOException ex) {
      System.out.println("Error: " + ex.getMessage());
      ex.printStackTrace();

    } finally {

      try {
        if (ftpClient.isConnected()) {
          ftpClient.logout();
          ftpClient.disconnect();
        }

      } catch (IOException ex) {
        ex.printStackTrace();
      }

    }
  }
}

For this example you have to download and add to the project the commons-net-3.6.jar file (or a new version of it):

If the upload is done successfully , you will see into the console, the following:

If the FTP server is stopped, you can see the following error: