10.15. Writing an FTP Client
Problem
You need to write a program to interact with an FTP server.
Solution
Use Commons Net FTPClient
to communicate
with
an FTP server. The following example retrieves the contents of the
file c64bus.gif
from
ftp.ibibilio.org
:
import org.apache.commons.io.IOUtils; import org.apache.commons.net.ftp.FTPClient; FTPClient client = new FTPClient( ); OutputStream outStream = null; try { // Connect to the FTP server as anonymous client.connect( "ftp.ibiblio.org" ); client.login( "anonymous", "" ); String remoteFile = "/pub/micro/commodore/schematics/computers/c64/ c64bus.gif"; // Write the contents of the remote file to a FileOutputStream outStream = new FileOutputStream( "c64bus.gif" ); client.retrieveFile( remoteFile, outStream ); } catch(IOException ioe) { System.out.println( "Error communicating with FTP server." ); } finally { IOUtils.closeQuietly( outStream ); try { client.disconnect( ); } catch (IOException e) { System.out.println( "Problem disconnecting from FTP server" ); } }
In the previous example, an instance of FTPClient
is created; the example then logs on to
ftp.ibibio.org
as
anonymous—
with no password—using the
connect( )
and login()
method on FTPClient
. The
full path to the remote file c64bus.gif
and an
OutputStream
are passed to retrieveFile()
, which then transfers the contents of the
c64bus.gif
to a local file. Once the file has
been retrieved, the FTPClient
is disconnected from
the server using the disconnect( )
method in a finally ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.