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. The technique is based on RFC 1738 specification which defines URL format for FTP access as follows:

ftp://user:password@host:port/path

This URL scheme is called FTP URL, where:

    • user: user name of a FTP account on the FTP server to connect to.
    • password: password corresponds to the user name.
    • host: host name or IP address of the FTP server.
    • port: port number on which the server is listening. Default is 21.
    • path: path of the remote file in the following form:

<cwd1>/<cwd2>/.../<cwdN>/<name>;type=<typecode>

Where:

        • <cwd1>, <cwd2>,…, <cwdN> are path elements which form a particular directory structure (cwd means change working directory).
        • <name>: file/directory name.
        • ;type=<typecode>: this part is optional. It 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, the client has to guess the appropriate mode.

For example, if you want to download a zip file Project.zip under path /project/2012 on the host www.myserver.com using user tom and password secret, construct the following URL:

ftp://tom:secret@www.myserver.com/project/2012/Project.zip;type=i

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

In Java, we use the URLConnection class to open a connection on a FTP URL, and then obtain the 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://tom:secret@www.myserver.com/project/2012/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 following program demonstrates how to use URLConnection class to download a file on a FTP server using FTP URL technique:

package net.codejava.ftp;

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

/**
 * This program demonstrates how to download a file from FTP server
 * using FTP URL.
 * @author www.codejava.net
 *
 */
public class FtpUrlDownload {
	private static final int BUFFER_SIZE = 4096;

	public static void main(String[] args) {
		String ftpUrl = "ftp://%s:%s@%s/%s;type=i";
		String host = "www.yourserver.com";
		String user = "tom";
		String pass = "secret";
		String filePath = "/project/2012/Project.zip";
		String savePath = "E:/Download/Project.zip";

		ftpUrl = String.format(ftpUrl, user, pass, host, filePath);
		System.out.println("URL: " + ftpUrl);

		try {
			URL url = new URL(ftpUrl);
			URLConnection conn = url.openConnection();
			InputStream inputStream = conn.getInputStream();

			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);
			}

			outputStream.close();
			inputStream.close();

			System.out.println("File downloaded");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

However, this technique has its own advantage and disadvantage as follows:

    •           Advantage: simple to use, does not require third party FTP library.
    •           Disadvantage: 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.

 

Related Java FTP File Download Tutorials:

 

Other Java File Download Tutorials:

 

Other Java FTP Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (FtpUrlDownload.java)FtpUrlDownload.java[ ]1 kB

Add comment

   


Comments 

#12Charles2024-10-25 21:55
I found that shifting service providers was actually the
very best auto insurance company technique to acquire cheap
car insurance. Looking into various firms led me to a great affordable car insurance planning.
Quote
#11Greeshma2020-11-01 06:04
Please give the code for downloading a csv file from an ftp server using ftpClient. When I tried I am able to download a text file successfully but not a csv file. The file is downloaded but with no content.
Quote
#10winpro2019-09-11 19:37
Thank you. It was helpful.
Quote
#9Sarith Nob2017-07-10 04:05
Hello!

When I type the ftp url into web browser it show the file.
But when I use the code above it doesn't work.

It always runs into IOException.

Is there any problem with it?

Thank you!
Quote
#8Naveend2017-05-13 08:51
My password has @ char in it and its getting error like
Error: For input string: "password@"
please suggest a soln
Quote