Using The FTP Client

Simple Example

This is a minimal example (with no error handling) that connects to an FTP server and lists the files on the server:

FTPClient client = new FTPClient();

client.connect( "server" );
client.login( "user", "pass" );

FTPFile files[] = client.listFiles();

for (FTPFile file : files) 
    System.out.println(file.getName());

Listing Files

The listFiles() method returns a directory listing of files in the current directory on the remote server.

Retrieving a File

There are a few different ways to download a file. The easiest method is to use the download() convenience method:

boolean success = client.download("remote", "local");

The second method takes an OutputStream which must be explicitly closed when the file transfer is complete.

// Open a stream for local file storage
OutputStream fos = new FileOutputStream("/tmp/readme.txt");
// Get the file from the remote server
client.retrieveFile("readme.txt", fos);
// close the output stream
fos.close();

The third method returns an InputStream, which must also be explicitly closed when the file transfer is completed. This method requires that you call completePendingCommand() when the file transfer is complete (in order to consume the server response status).

BufferedInputStream bis = new BufferedInputStream(client.retrieveFileStream("readme.txt"));
byte[] buf = new byte[8192];
int read = 0;
while ((read = bis.read(buf)) != -1)
	System.out.println(new String(buf,0,read));
bis.close();

// This should be done before executing subsequent commands
client.completePendingCommand();

Setting file transfer mode

In order to explicitly set ASCII or binary file type on the file download, use setFileType().

import org.netling.ftp.FTP.FileType;

// Binary (I) file type
client.setFileType(FileType.BINARY);

// ASCII (A) file type
client.setFileType(FileType.ASCII);

Storing a File

The easiest way to store a file is to use the upload() command:

boolean success = client.upload("remote", "local");

As per the file download commands, the FTPClient class provides some lower-level methods for file uploading. See the storeFile() method for an example.

Setting the character set encoding

The FTPClient class supports setting arbitrary character set encoding for the control connection. ALthough historically FTP servers have supported ASCII character sets only, an FTP server that implements RFC 2640 supports UTF8 (and will make this known via the FEAT command).

To set the control encoding to UTF-8, use:

client.setControlEncoding("UTF8");