Monday, 28 March 2016

How to read files on FTP using org.apache.commons.net.ftp.FTPClient in Java

How to read a file over FTP in Java using org.apache.commons.net.ftp.FTPClient

File transfer protocol (FTP) is a used to transfer files between clients and servers.
The apache commons API provides the org.apache.commons.net.ftp.FTPClient which helps us to carry out various FTP operations very easily.


Step 1:
Download the commons-net-3.4 jar file from here and put it in your project build path:
http://central.maven.org/maven2/commons-net/commons-net/3.4/commons-net-3.4.jar

For Maven and other dependencies:



Step 2:
Below is a very simple example of FTP in Java.
  • Please change the ftpUrl and defaultPort to your own.
  • Use changeWorkingDirectory method to go to the directory of the file before accessing the file. Default path after login is "ROOT" directory.
  • In retrieveFileStream pass the file name

File: ReadFtpFileExample.java

package net.codermag.sample;

import java.io.InputStream;
import java.util.Scanner;
import org.apache.commons.net.ftp.FTPClient;

public class ReadFtpFileExample {

 public static void main(String[] args) {

  String ftpUrl = "ftp.funet.fi";
  int defaultPort = 21;

  String user = "username";
  String pass = "password";
  
   try {
           //Opening the FTP connection and logging in
           FTPClient ftpClient = new FTPClient();
           ftpClient.connect(ftpUrl, defaultPort);
           ftpClient.login(user, pass);
           ftpClient.enterLocalPassiveMode();
    
           //if the file is not in root we need to change directory
           ftpClient.changeWorkingDirectory("/pub/standards/RFC/");
           InputStream inputStream = ftpClient.retrieveFileStream("rfc959.txt");
           Scanner sc = new Scanner(inputStream);
      
      
           //Reading the file line by line and printing the same
           while (sc.hasNextLine()) 
           System.out.println(sc.nextLine());
      
      
           //Closing the channels
           sc.close();
           inputStream.close();
   }
  
  catch (Exception e) 
  {
   e.printStackTrace();
  } 
  
 }

}