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:
<cwd1>/<cwd2>/.../<cwdN>/<name>;type=<typecode>
Where:
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: