Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java FTP: How to download file with Java

This article describes how to use java.net.URLConnection class to download a remote file from a FTP server, without using a third party library such as Apache Commons Net, Tomcat etc.

This technique is based on RFC1738 specification which defines URL format for FTP access. This application downloads a file from the server and list out the size of downloading file and the time consumed in the downloading.

Objective

In this tutorial, we will learn:

  • What is FTP?
  • How do we java code to download a file from your FTP server?
  • Advantages and Disadvantages

What is FTP?

FTP (File Transfer Protocol) is the simplest and most secure way to exchange files over the Internet. FTP is a fast and reliable method for transferring files between two remote computers, using the Internet. A basic FTP connection consists of a remote computer (the client) calling an FTP server. FTP connections transmit information in two ways: the client may upload content from the server or download content to the server.

In order to make a connection, simply direct the “client” to connect to a specific FTP server.

In order to transfer a file (upload or download) through FTP:

  • Log in to a remote computer that has been configured as an FTP server.
  • Enter a username and password to gain access to the remote system.
  • Select the particular directory on the remote system, which contains the file you wish to download or upload.
  • Transfer the file to or from the system.

How do we java code to download a file from your FTP server?

In this article we will learn how to use the class i.e. java.net.URLConnection to download a remote file from a FTP server, without using a third party servers like Apache, Tomcat Servers. The technique is based on RFC1738 specification which defines URL format for FTP access as follows: ftp://username:password@hostname:port/path

This URL scheme is called FTP URL, where:

  • username : is the user name of a FTP account on the FTP server to connect to.
  • password : is the password corresponds to the user name.
  • hostname : is the host name or IP address of the FTP server.
  • port : Is the port number on which the server is listening. [default port is 21]
  • path : Path of the remote file in the following form:
<dir1>/<dir2>/.../<dirN>/<name>;type=<typecode>

Where:

  • <dir1>/<dir2>/.../<dirN> : are path elements which form a particular directory structure (the word <dir> means directory).
  • <name> : file/directory name.
  • :type=<typecode> : this is the optional part. This part specifies the transfer mode where typecode can be one of the characters: a (ASCII - text mode), i (IMAGE - binary mode), d (Directory listing). If this part is omitted or regretted, the client has to guess the appropriate mode.

For example, if you want to download a zip file Project.zip under path /myproject/2013 on the host www.myclientserver.com using user oracle and password secret, construct the following URL: ftp://oracle:secret@www.myclientserver.com/myproject/2013/Project.zip;type=i

Paste that URL into browser’s address bar and it will handle the file download.

In Java, we use the class name: URLConnection to open a connection on a FTP URL, and after that obtain a input stream of the opened connection to read bytes data. Use a file output stream to save the bytes into a file.

For example:

  • String ftpUrl = "ftp://oracle:secret@www.myclientserver.com/myproject/2013/Project.zip;type=i";
  • String saveFile = "Project.zip";
  • URL url = new URL(ftpUrl);
  • URLConnection conn = url.openConnection();
  • InputStream inputStream = conn.getInputStream();
  • FileOutputStream outputStream = new FileOutputStream(saveFile); // reads from inputStream and write to outputStream

The below program describes how to use class URLConnection to download a file on a FTP server using FTP URL technique:

Moreover, this technique has its own advantages and disadvantages which are given below:

Listing 1: Download.java

import java.io.FileOutputStream ;
import java.io.IOException ;
import java.io.InputStream ;
import java.net.URL ;
import java.net.URLConnection ;
import java.io.File ;

class Download{
	private static final int BUFFER_SIZE = 4096 ;
	public void download(){    //this is a function
		long startTime = System.currentTimeMillis() ;
		String ftpUrl = ftp://**username**:**password**@filePath ;
		String file= "filename" ; // name of the file which has to be download
		String host = host_name ; //ftp server
		String user = "username" ; //user name of the ftp server
		String pass = "**password" ; // password of the ftp server

		String savePath = "c:\\" ;
		ftpUrl = String.format(ftpUrl, user, pass, host) ;
		System.out.println("Connecting to FTP server") ;

		try{
			URL url = new URL(ftpUrl) ;
			URLConnection conn = url.openConnection() ;
			InputStream inputStream = conn.getInputStream() ;
			long filesize = conn.getContentLength() ;
			System.out.println("Size of the file to download in kb is:-" + filesize/1024 ) ;

			FileOutputStream outputStream = new FileOutputStream(savePath) ;

			byte[] buffer = new byte[BUFFER_SIZE] ;
			int bytesRead = -1 ;
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, bytesRead) ;
			}
			long endTime = System.currentTimeMillis() ;
			System.out.println("File downloaded") ;
			System.out.println("Download time in sec. is:-" + (endTime-startTime)/1000)  ;
			outputStream.close() ;
			inputStream.close() ;
		}
		catch (IOException ex){
			ex.printStackTrace() ;
		}
	} 
}

Listing 1 defines a java file “Download.java” that defines a mechanism to get connected with the ftp server using given url with the valid username and password. Once the connected is established with the given ftp url, the connection will be authenticated using the submitted username and password given into the ftp url. A java.net java API is used to establish to cover networking part of the application.

This class defines class variable:

  • BUFFER_SIZE: An integer type static variable that defines a buffer size of the stream to be kept downloading file content at a time.

And a method:

download(): A method that invoke downloading connection and download a file from the server. It also defines a set of variables:

  • startTime: A long type variable that is initialized by current system time, this variable is used to list out the time consumed in the downloading.
  • ftpUrl: A string type variable to hold the url information that will be used to connect with the ftp host.
  • file: A string type variable that name the downloading file.
  • host: A string type variable that list the name of host that is to be connected.
  • user: A string type variable to hold username information.
  • password: A string type variable to hold password information.
  • savePath: A string type variable that holds the file location to save downloading file.
  • outputStream: A FileOutputStream type variable that output the downloading file to be saved in the given system location using “savePath” variable.
  • url: A URL class type variable that create request to hit on the given host using ftpUrl.
  • buffer: A byte array of size BUFFER_SIZE.
  • bytesRead: An integer type variable to hold information of receiving bytes from the server.
  • endTime: An integer type variable to current system time, when a file downloading ends.

Once the file has been downloaded, the downloading consumed time will be listed with the downloaded file size. The file will be read byte by byte using listed logic below:

while((bytesRead = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, bytesRead) ;
		}

Once the file has been donwlaoded, it is our responsibility to close the opened FileOutputStream. To close the stream, we use close() method defined into FileOutputStream class.

An inputstream is used to get the data from the ftp server, it will accepts data in bytes stream using connection class method. To get byte stream, getInputStream() method is used. To get the downloading file getContentLength() method of connection is used. As we opened input stream, it is our responsibility to close this stream. To close input stream, close() method of InputStream class is used.

Once the file has been downloaded, the consumed tile is calculated using by subtracting startTime from endTime and divide it by 1000 as (endTime - startTime)/1000).

Listing 2: FtpUrlDownload.java

public class FtpUrlDownload{
              public static void main(String[] args){
	           Download d1 = new Download() ;
		   d1.download() ;
		   try{
                              Thread.sleep(500) ;
	               }
 	               catch(Exception e) { 
                                System.out.println(c);
                           }
       }
 }

Listing 2 defines a java file “FtpUrlDownload.java” that creates an instance of “Download” class and class a method named “download()” to download a file from given server url into download class. This class uses connection exception mechanism that may be occurred while trying to establish connection with the server, receiving data from ftp host and saving the downloaded file.

Advantages:

Simple to use, does not require third party FTP tool or application server.

Disadvantages:

Less flexibility and less control, there is no way to check FTP server’s response code. If the download fails in the middle, we have to start over the download because it’s impossible to resume the upload.

Conclusion:

Using this article, we learn about FTP protocol and its use. Here we created file download application using java.net API using to download an application for the given url and user authentication information. In this application, we came to learn about the file downloading process. We learn, how we calculate the size of downloading file, the time consumed in file downloading and save the file to system.



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login