How do I download file from FTP server?

This example demonstrates how to download a file from FTP server. To download a file, we first connect to the FTP server and then login by supplying the username and password. To download the file we call retrieveFile() method of the FTPClient object. This method takes two parameters, the remote filename and an OutputStream of the local file where the download to be saved.

package org.kodejava.commons.net;

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

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FTPDownloadDemo {
    public static void main(String[] args) {
        // The local filename and remote filename to be downloaded.
        String filename = "data.txt";

        FTPClient client = new FTPClient();
        try (OutputStream os = new FileOutputStream(filename)) {
            client.connect("ftp.example.com");
            boolean login = client.login("demo", "password");
            if (login) {
                System.out.println("Login success...");

                // Download file from FTP server.
                boolean status = client.retrieveFile(filename, os);
                System.out.println("status = " + status);
                System.out.println("reply  = " + client.getReplyString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

If the download process was success, you will see the following output printed:

status = true
reply  = 226 Transfer complete.

Maven Dependencies

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.10.0</version>
</dependency>

Maven Central

Wayan

19 Comments

    • The download path can be defined in the FileOutputStream object. You can pass a string with a full path or you can create File object that define the full path where the download file will be stored.

      Reply
  1. I tried the code but my app has stopped 🙁 The changes that I made with the code are: with the server name and login user as well as the directory for the file in the server.

    When i call this class in the mainActivity what should I send? I call it in my mainActivity like this:

    startActivity(new Intent(MainActivity.this, FTPDownloadFileDemo.class));
    

    Can you help me?

    Reply
  2. Hi Victor,

    Try to get the download status and the reply code from the FTP server by adding the following code. This will show if the download process success or failed.

    boolean status = client.retrieveFile(filename, os);
    System.out.println("status = " + status);
    System.out.println("reply  = " + client.getReplyString());
    
    Reply
  3. I’ve been trying different ways for several days and got stuck. I log in to FTP, but I cannot download data from the file. I don’t want to save them locally, I just want to download them, put them into an array, count them and save them again on FTP or just display or print them.

    Here are my attempts with the code:

    fun zapisStringFtp() {
        executorService.execute(Runnable {
            val client = FTPClient()
            client.connect("www.test.pl", 21)
            val login: Boolean = client.login("login", "password")
            client.enterLocalPassiveMode()
            //val os: InputStream = ByteArrayInputStream(text.toByteArray(Charsets.UTF_8))
            val os: OutputStream = FileOutputStream("kotlin/mk.txt")
            //val status = client.retrieveFile("kotlin/Maciek_P1.txt",os)
            //val status  = client.retrieveFileStream("kotlin/Maciek_liczby.txt")
            val status: Boolean = client.retrieveFile("kotlin/Maciek_liczby.txt", os)
            val sciezka = client.replyString
            val plik_1 = File(sciezka)
    
            if (login) {
                System.out.println("Login Succes")
                System.out.println("Status=" + status)
                //client.storeFile("kotlin/" + "aaa", status)
                println(" Sciezka=  " + sciezka)
                println(" plik_1  " + plik_1)
                client.logout()
                client.disconnect()
            }
        })
    }
    
    Reply
    • Preferably, if it was possible to download data from the file directly from ftp, without saving (android creates problems with saving files on the device).

      Reply
    • Hi Maciekk,

      What about the following snippet? We convert the output stream into string and then process it.

      import org.apache.commons.net.ftp.FTPClient
      import java.io.ByteArrayOutputStream
      
      fun main() {
          val client = FTPClient()
          client.connect("localhost")
      
          val login = client.login("demo", "password")
          if (login) {
              println("Login success...")
      
              ByteArrayOutputStream().use {
                  client.retrieveFile("data.txt", it)
                  val data = String(it.toByteArray())
                  println(data);
      
                  val numbers = data.split(",")
                  for (number in numbers) {
                      println(number)
                  }
      
                  client.logout()
                  client.disconnect()
              }
          }
      }
      
      Reply
      • Thank you very much again!
        You are my best Kotlin and Android teacher. 🙂
        Of course the coffee is running 🙂

      • I was able to write the numbers from the txt file to the array, but I can’t get the quantity to determine the size of the array.

        ByteArrayOutputStream().use {
            client.retrieveFile(plik, it)
            val data = String(it.toByteArray())
        
            //println("plik = $plik")
            println("data= " + data)
            println("----------------")
        
            val numbers = data.split(",")
        
            var liczba_elementow = 0
            for (number in numbers) {
        
                liczba_elementow += 1
        
                println("number= " + number)
                println("numbers= " + numbers)
                var tablica_Maciekk = Array(4, { i -> number })
        
        
                // odczyt tablicy
                /* for ( n in tablica_Maciekk )
                 {
                     print("Wartosci z tablicy= " + "\n" + n)
                     println("Ilosc elementow= "  + number)
                 }*/
                println("liczba elemnetow " + liczba_elementow)
            }
        }
        
      • I did it but a bit weird 🙂

        val numbers = data.split(",")
        val test = data.lines()
        val ilosc_liczb = test.size - 1
        for (number in data) {
            println("test= " + test)
            println("ilosc liczb = " + ilosc_liczb)
            println("numbers= " + numbers)
            var tablica_Maciekk = Array(ilosc_liczb, { i -> number })
        }
        
      • However, wrong. I can’t write these numbers from a file to an array. the program prints all numbers (number)
        77
        16
        33

        but I can’t put them in the board.

      • I try different ways:

        var liczba = 0
        //val numbers = data.split(",")
        val numbers = data.split(",").toTypedArray()
        println("numbers=" + numbers)
        var tablica = IntArray(16)
        var a = 0
        for (number: String in numbers) {
            liczba = number.toInt()
            //var tablica = arrayListOf(16)
            tablica.set(a, liczba)
            a += 1
        
            //println(number)
            for (n in tablica) {
                println("tablica = $n")
            }
        }
        

        The problem is with “77
        and last “.

        E/AndroidRuntime: FATAL EXCEPTION: pool-2-thread-1
            Process: com.mmajka.composemvvmsample, PID: 7201
            java.lang.NumberFormatException: Invalid int: "77
            16
            33
            36
            73
            69
            12
            69
            83
            71
            58
            86
            27
            10
            77
            65
            "
                at java.lang.Integer.invalidInt(Integer.java:138)
        

        I don’t know how to get rid of “”.

Leave a Reply to WayanCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.