Monday, 28 March 2016

How to read files on FTP using in Java

How to read a file over FTP in Java using

File transfer protocol (FTP) is a used to transfer files between clients and servers.
The apache commons API provides the 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:

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


package net.codermag.sample;

import java.util.Scanner;

public class ReadFtpFileExample {

 public static void main(String[] args) {

  String ftpUrl = "";
  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);
           //if the file is not in root we need to change directory
           InputStream inputStream = ftpClient.retrieveFileStream("rfc959.txt");
           Scanner sc = new Scanner(inputStream);
           //Reading the file line by line and printing the same
           while (sc.hasNextLine()) 
           //Closing the channels
  catch (Exception e) 


No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.