A simple Java FTP connection + file download and upload

Java programming topics

A simple Java FTP connection + file download and upload

Postby Nipuna » Sat Jan 14, 2012 1:27 pm

When working with FileZilla.

I thought to find a simple FTP client that is written in Java and read its code.

So I was able to find one and it seems a great code since the coder has commented every single thing of it very well.

So here goes it.

Code: Select all
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;
    }
  }
 

}
User avatar
Nipuna
Promo Team
Promo Team
 
Posts: 2219
Joined: Mon Jan 04, 2010 2:32 pm
Cash on hand: 86,482.70
Bank: 252,701.40
Location: Deraniyagala,SRI LANKA
Medals: 2
EC_Bronze_Star (1) EC_Achievment (1)

Invitations sent: 5
Registered friends: 0
Highscores: 1
Reputation point: 33
Staff Sergeant

Re: A simple Java FTP connection + file download and upload

Postby Saman » Sat Jan 14, 2012 8:59 pm

Looks like you are expertising Java these days which is good to see. Keep up the good work!
User avatar
Saman
Support Team
Support Team
 
Posts: 784
Joined: Fri Jul 31, 2009 5:02 pm
Cash on hand: 152,542.40
Location: Mount Lavinia
Medals: 1
EC_Achievment (1)

Invitations sent: 44
Registered friends: 1
Reputation point: 37
Staff Sergeant

Re: A simple Java FTP connection + file download and upload

Postby Nipuna » Sun Jan 15, 2012 2:46 am

Yeah step by step.   :)  

But I actually read this code didn't write it or run it  :)  This is still little heavy for me  :)

Thank you
User avatar
Nipuna
Promo Team
Promo Team
 
Posts: 2219
Joined: Mon Jan 04, 2010 2:32 pm
Cash on hand: 86,482.70
Bank: 252,701.40
Location: Deraniyagala,SRI LANKA
Medals: 2
EC_Bronze_Star (1) EC_Achievment (1)

Invitations sent: 5
Registered friends: 0
Highscores: 1
Reputation point: 33
Staff Sergeant

Re: A simple Java FTP connection + file download and upload

Postby SemiconductorCat » Mon Jan 23, 2012 8:59 pm

ya , I'm not going to init_java_c_war() inside this module.
But whatever the programming language you learn , use to learn to read somebody
eles's code Nipuna. That will made your patience and concentration and also it will
made you a good programmer.

A book like this may very useful too.
http://www.amazon.com/Code-Complete-Pra ... 0735619670


[I'm a Sinhalese person , so I can't promote or send you the links to DN. But you know
what I'm talking about. ]
User avatar
SemiconductorCat
 
Posts: 362
Joined: Mon Aug 22, 2011 3:12 pm
Cash on hand: 18,594.40
Location: currently in hyperspace

Invitations sent: 0
Registered friends: 0
Reputation point: 6
Corporal

Re: A simple Java FTP connection + file download and upload

Postby Nipuna » Mon Jan 23, 2012 9:10 pm

Thank you for the book.

I'll download it  ;)
User avatar
Nipuna
Promo Team
Promo Team
 
Posts: 2219
Joined: Mon Jan 04, 2010 2:32 pm
Cash on hand: 86,482.70
Bank: 252,701.40
Location: Deraniyagala,SRI LANKA
Medals: 2
EC_Bronze_Star (1) EC_Achievment (1)

Invitations sent: 5
Registered friends: 0
Highscores: 1
Reputation point: 33
Staff Sergeant


Return to Java Programming

Who is online

Users browsing this forum: No registered users and 0 guests