How to transfer directly from/to memory

One of the advantages of integrating FTP functionality directly into a product rather than using stand-alone FTP applications is that data can be transferred directly to and from memory. This is particularly useful when transferring dynamic content needs, such as the results of database queries and other application data.

FTPClient, SSLFTPClient, and SSHFTPClient offer three alternatives for memory transfers: byte-arrays, streams and FTP streams. Byte-arrays are generally easier to deal with but do not facilitate streaming. In other words, the data must be fully generated and stored in a byte-array before being transferred. This is fine when memory usage is not an issue, but if it is necessary to limit memory usage then streams should be used.

Byte-Array Transfers are performed using the (overloaded) get and put methods. They simply take the byte-array and/or the remote file-name as parameters.

string s = "Hello world";
byte[] bytes = s1.getBytes();
ftp.put(bytes, remoteFileName);

Because all of the transferred data is stored in memory, byte array transfers should be avoided for large files.

FTP Streams are subclasses of InputStream and OutputStream, and can be used in the same way. They are described in How to transfer using FTP streams.

Stream Transfers allow the local data being transferred to be supplied as an InputStream, and the remote data to be written to a local OutputStream.

To transfer streams, the overloaded methods get and put can be used as shown below:

The following shows how a file can be wrapped in a stream and then uploaded:

InputStream srcStream = new FileInputStream(localFilename);
ftp.put(srcStream, remoteFilename);

Similarly, the following shows how a file can be downloaded to a stream:

OutputStream outStream = new FileOutputStream(localFilename);
ftp.get(outStream, remoteFilename);

The above examples of files wrapped in streams are trivial, however they illustrate how the API can be used.