Programmer's Corner - Java Source Code Sample

Backup and Security Solutions 10% off all products with promo code: VISI-P1YR
Get the Programmer's Corner FireFox Search Plug-In

FTP Upload Client - Java

G Rowland

http://www.angelfire.com/ego/rowland/

growland84@hotmail.com

         

         

Upload a file to an FTP server via java.net.URLConnection





// FTPupload.java by Rowland http://www.home.comcast.net/~rowland3/
// Upload a file via FTP, using the JDK.

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


class FTPclientConn {
    public final String host;
    public final String user;
    protected final String password;
    protected URLConnection urlc;

    public FTPclientConn(String _host, String _user, String _password) {
  host= _host;  user= _user;  password= _password;
  urlc = null;
    }
    protected URL makeURL(String targetfile) throws MalformedURLException  {
  if (user== null)
      return new URL("ftp://"+ host+ "/"+ targetfile+ ";type=i");
  else
      return new URL("ftp://"+ user+ ":"+ password+ "@"+ host+ "/"+ targetfile+ ";type=i");
    }

    protected InputStream openDownloadStream(String targetfile) throws Exception {
  URL url= makeURL(targetfile);
  urlc = url.openConnection();
  InputStream is = urlc.getInputStream();
  return is;
    }

    protected OutputStream openUploadStream(String targetfile) throws Exception {
  URL url= makeURL(targetfile);
  urlc = url.openConnection();
  OutputStream os = urlc.getOutputStream();
  return os;
    }

    protected void close() {
  urlc= null;
    }
}


public class FTPupload {
    protected FTPclientConn cconn;
    public final String localfile;
    public final String targetfile;

    public FTPupload(String _host, String _user, String _password,
         String _localfile, String _targetfile) {
  cconn= new FTPclientConn(_host, _user, _password);
  localfile= _localfile;
  targetfile= _targetfile;
  doit();
    }
    public FTPupload(String _host, String _user, String _password, String _file) {
  cconn= new FTPclientConn(_host, _user, _password);
  localfile= _file;
  targetfile= _file;
  doit();
    }

    protected void doit() {
  try {
      OutputStream os= cconn.openUploadStream(targetfile);
      FileInputStream is=  new FileInputStream(localfile);
      byte[] buf= new byte[16384];
      int c;
      while (true) {
    //System.out.print(".");
    c= is.read(buf);
    if (c<= 0)  break;
    //System.out.print("[");
    os.write(buf, 0, c);
    //System.out.print("]");
      }
      os.close();
      is.close();
      cconn.close(); // section 3.2.5 of RFC1738
  } catch (Exception E) {
      System.err.println(E.getMessage());
      E.printStackTrace();
  }
    }

    public static void main(String args[]) {
  // Usage: FTPupload host, user, password, file
  new FTPupload(args[0], args[1], args[2], args[3]);
    }

}