jFTP, Tutorial II

Chapter I: Hello FTP
Chapter II: FTP files
   Copying file
   Reading and writing a file

This chapter shows how to read and write remote files.

Very important note! One open ftp connection can handle only one data transfer at given time! This means that if you plan to open multiple files at time you have to open multiple connections one for each file you want to read or write simultaneously. (There are specialized FtpInput/OutputStream one step constructors supplied to overcome this pain.)

Anyway, you always need to consider this fact. Never open concurrent data transfers on same ftp instance.

Only corresponding pieces of code are shown, assuming that connect was already done before.


Copying file

Static method CoLoad.copy can be used to download file. Simply switching parameter order carries out upload.

   /* source FtpFile remote file */
   CoFile file = new FtpFile("/Welcome",cl);

   /* destination LocalFile home-dir/Welcome */
   CoFile to = new LocalFile(System.getProperty("user.dir"),file.getName());

   /* download /Welcome file to home-dir/Welcome */
   CoLoad.copy(to,file);

Multiple files or directories can be copied by CoLoad.copy using array of CoFile[] objects as a source parameter. Of course destination parameter must denote a directory in this case.

Note: If array of CoFile[] objects contains CoFile object which denotes a directory, its contents will be copied recursively.

Also a CoLoad.delete method is supplied for deleting files recursively.

Download this example FtpLoadTest.


Reading and writing a file

Following piece of code shows how to use FtpInputStream to read contents of a remote file. Using FtpOutputStream writing to a remote file can be carried in very similar way.

Remember that you always need to use BufferedReader / BufferedWriter for achieving good performance. Respectively use BufferedInputStream / BufferedOutputStream for reading or writing binary files.

Similarly, you can use FtpListInputStream to read contents of directory in text format.

   FtpInputStream is = null;
   /* source FtpFile remote file */
   FtpFile file = new FtpFile("/Welcome",cl);

   /* open ftp input stream */
   is = new FtpInputStream(file);
   BufferedReader br = new BufferedReader
      (new InputStreamReader(is));

   /* read ftp input stream */
   while ((line = br.readLine()) != null)
      System.out.println(line);

   /* close reader */
   br.close();

Important note! Both Ftp.close and FtpInputStream.close methods must be called.

Download this example FtpStreamTest.