A simple Java FTP connection + file download and upload

The Java or JDK comes with NO support of any official API for FTP connection. But there is an internal that comes in the sun.net package, but this is NOT well-documented, and you will hardly find how to use other methods within the sun.net.ftp.FtpClient class.

The sun.net.ftp.FtpClient actually sticks to the RFC959. But once you use this to build the class within your Java program, you will always get the complain that this internal API is likely to be discarded in the future versions of JDK.

But Java has the implementation of RFC1738, which is the URL spec, that can be used for initiating FTP connections, download and upload files. In order to be free from the hassle that an upgrade of the JDK might get your program to fail to work, due to it uses sun.net.ftp.FtpClient, therefore it’s best to use the URL spec. I’ve got a simple Java file that does the simple FTP connection, and opens an InputStream for downloading file, or opens an OutputStream for uploading file as follows:

import java.net.*;
import java.io.*;

public class SimpleFTPClient
{

  /** The URL connection object */
  private URLConnection m_client;

  /** The FTP host/server to be connected */
  private String host;

  /** The FTP user */
  private String user;

  /** The FTP user’s password */
  private String password;

  /** The remote file that needs to be uploaded or downloaded */
  private String remoteFile;

  /** The previous error message triggered after a method is called */
  private String erMesg;

  /** The previous success message after any method is called */
  private String succMesg;

  public SimpleFTPClient(){}

  /** Setter method for the FTP host/server */
  public void setHost (String host)
  {
    this.host = host;
  }

  /** Setter method for the FTP user */
  public void setUser (String user)
  {
    this.user = user;
  }

  /** Setter method for the FTP user’s password */
  public void setPassword (String p)
  {
    this.password = p;
  }

  /** Setter method for the remote file, this must include the sub-directory path relative
   to the user’s home directory, e.g you’e going to download a file that is within a sub directory
   called “sdir”, and the file is named “d.txt”, so you shall include the path as “sdir/d.txt”
  */
  public void setRemoteFile (String d)
  {
    this.remoteFile = d;
  }

  /** The method that returns the last message of success of any method call */
  public synchronized String getLastSuccessMessage()
  {
    if (succMesg==null ) return “”; return succMesg;
  }

  /** The method that returns the last message of error resulted from any exception of any method call */
  public synchronized String getLastErrorMessage()
  {
    if (erMesg==null ) return “”; return erMesg;
  }

  /** The method that handles file uploading, this method takes the absolute file path
   of a local file to be uploaded to the remote FTP server, and the remote file will then
   be transfered to the FTP server and saved as the relative path name specified in method setRemoteFile
   @param localfilename – the local absolute file name of the file in local hard drive that needs to
   FTP over
  */
  public synchronized boolean uploadFile (String localfilename)
  {
    try{

      InputStream is = new FileInputStream(localfilename);
      BufferedInputStream bis = new BufferedInputStream(is);
      OutputStream os =m_client.getOutputStream();
      BufferedOutputStream bos = new BufferedOutputStream(os);
      byte[] buffer = new byte[1024];
      int readCount;

      while( (readCount = bis.read(buffer)) > 0)
      {
            bos.write(buffer, 0, readCount);
      }
      bos.close();

      this.succMesg = “Uploaded!”;

      return true;
    }
    catch(Exception ex)
    {
      StringWriter sw0= new StringWriter ();
      PrintWriter p0= new PrintWriter ( sw0, true );
      ex.printStackTrace ( p0 );
      erMesg = sw0.getBuffer().toString ();

      return false;
    }
  }

  /** The method to download a file and save it onto the local drive of the client in the specified absolut path
   @param localfilename – the local absolute file name that the file needs to be saved as */
  public synchronized boolean downloadFile (String localfilename)
  {
    try{
      InputStream is = m_client.getInputStream();
      BufferedInputStream bis = new BufferedInputStream(is);

      OutputStream os = new FileOutputStream(localfilename);
      BufferedOutputStream bos = new BufferedOutputStream(os);

      byte[] buffer = new byte[1024];
      int readCount;

      while( (readCount = bis.read(buffer)) > 0)
      {
        bos.write(buffer, 0, readCount);
      }
      bos.close();
      is.close (); // close the FTP inputstream
      this.succMesg = “Downloaded!”;

      return true;
    }catch(Exception ex)
    {
      StringWriter sw0= new StringWriter ();
      PrintWriter p0= new PrintWriter ( sw0, true );
      ex.printStackTrace ( p0 );
      erMesg = sw0.getBuffer().toString ();

      return false;
    }
  }

  /** The method that connects to the remote FTP server */
  public synchronized boolean connect()
  {
    try{

    URL url = new URL(“ftp://”+user+”:”+password+”@”+host+”/”+remoteFile+”;type=i”);
    m_client = url.openConnection();

    return true;

    }
    catch(Exception ex)
    {
      StringWriter sw0= new StringWriter ();
      PrintWriter p0= new PrintWriter ( sw0, true );
      ex.printStackTrace ( p0 );
      erMesg = sw0.getBuffer().toString ();
      return false;
    }
  }
  

}

If you can’t read the above, copy it to a text pad or note pad for better reading. Click here (works in IE only) to copy code now!

And to use the above class for downloading or uploading file, you just need the simple few lines of code as follows:

1. Initiate the FTP connection first as follows, set the FTP server host name or IP address, and the user name and password, and call the connect method to connect to the FTP server

  SimpleFTPClient f= new SimpleFTPClient ();
  f.setHost(”remoteftpserver.com”);
  f.setUser(”ftpuser”);
  f.setPassword(”ftpuserpass2009″);
  boolean connected=f.connect();

2. If you wanna upload a file, you need to set the file path relative to the FTP user’s home directory. For example, to upload a file into the sub folder “public_html” and the file to be named/saved as “u.txt”

/** Set the remote file name */
f.setRemoteFile(”public_html/u.txt”);
if ( connected){
  // Upload a file from your local drive, lets say in “c:/ftpul/u.txt”
  if (f.uploadFile(”c:/ftpdl/u.txt”))
    // display the message of success if uploaded
  System.out.println(f.getLastSuccessMessage ());
  else
    System.out.println(f.getLastErrorMessage ());
  }
  else
  // Display any connection exception, if any
    System.out.println(f.getLastErrorMessage ());

3. Similarly, if you wanna download a file, you need to set the file path relative to the FTP user’s home directory. For example, to download a file from the sub folder “download” and the file to be downloaded is “dl.txt”

/** Set the remote file name */
f.setRemoteFile(”download/dl.txt”);
if ( connected){
  // The downloaded file to be saved to the local drive
  // as mydl.txt and in the subfoler c:\ftpdownloads
  if (f.downloadFile(”c:/ftpdownloads/mydl.txt”))
    // display the message of success if uploaded
    System.out.println(f.getLastSuccessMessage ());
  else
    System.out.println(f.getLastErrorMessage ());
}
else
  // Display any connection exception, if any
  System.out.println(f.getLastErrorMessage ());


Enter your email address to subscribe our newsletter or feed for FREE:

Delivered by FeedBurner


Bookmark with:

[Delicious]    [Digg]    [Reddit]    [Facebook]    [StumbleUpon]

0 Responses to “A simple Java FTP connection + file download and upload”


  1. No Comments

Leave a Reply

You must login to post a comment.