Solved

Listing and retrieving files on a FTP directory.

Posted on 2001-06-14
10
1,670 Views
Last Modified: 2011-09-20
Hi,

I have an interesting challenge. I need some code that will (using FTP) return a list of files in a directory, download said files, and delete said file.  I have mastered FTP'ing files to a remote directory; now I need to figure out how to do the reverse.  If more details are needed let me know.

Thanks,

P.S. I am currently using sun.net.ftp.FtpClient.
0
Comment
Question by:CaptainKirk
  • 4
  • 4
  • 2
10 Comments
 
LVL 1

Expert Comment

by:rajendra_rathod
ID: 6193965
Hi,

The following code may help u.

import java.net.*;
import java.io.*;
import java.util.*;
// ----------------------------------------------------------------------------|
// Ftp class wrtiten based on RFC 959.
//
// The following commands based on RFC 959 have been implemented.
//
//         CDUP - Change to Parent Directory
//         SMNT - Structure Mount
//         STOU - Store Unique
//         RMD  - Remove Directory
//         MKD  - Make Directory
//         PWD  - Print Directory
//         SYST - System
//         TYPE - Type, binary, ascii EBSIDC
//         RETR - Retrieve a file
//         CWD  - Change working directory.
//                  NLST - Send directory listing.
//         PORT - Set the port number.
//                  SITE - Retrieve site info from remote host.
//         ABOR - Abort connection.
//         LIST - Get a directory lising from remote host.
//         STOR - Store a file on the target machine.
//
//         < Ftp process diagram. Shows the flow of commands and
//         < responses that are exchanged between the client and
//         < remote host. Note: this does not support file
//         < transfer between two remote hosts. The user of this
//         < process must be logged in to the client side and
//         < have the proper file permissions on both the remote
//         < host and the client to be able to ftp files between
//         < the client and server.
//
//                                                -------------
//                                            |/---------\|
//                                            ||   User  ||    --------
//                                            ||Interface|<--->| User |
//                                            |\----^----/|    --------
//                  ----------                |     |     |
//                  |/------\|  FTP Commands  |/----V----\|
//                  ||Server|<---------------->|   User  ||
//                  ||  PI  ||   FTP Replies  ||    PI   ||
//                  |\--^---/|                |\----^----/|
//                  |   |    |                |     |     |
//      --------    |/--V---\|      Data      |/----V----\|    --------
//      | File |<--->|Server|<---------------->|  User   |<--->| File |
//      |System|    || DTP  ||   Connection   ||   DTP   ||    |System|
//      --------    |\------/|                |\---------/|    --------
//                  ----------                -------------
//
// ----------------------------------------------------------------------------|
public class Ftp {
   
  public static final int FTP_PORT = 21;
   
  static int  FTP_SUCCESSFULL  = 1;
  static int  FTP_TRY_AGAIN    = 2;
  static int  FTP_ERROR        = 3;
   
  public String       m_strPassword = null;
  public String       m_strUserID = null;
  public String               m_strHost = null;
  private String      m_strCurrentCommand;
   
  private boolean     m_bPassiveMode = false;
  private boolean     m_bBinaryMode = false;
  private boolean     m_bReplyPending = false;
  private Socket      m_Socket = null;
   
   
   
  public String       m_strMsg;
  public PrintWriter  m_ServerSideOutput;
  public InputStream  m_ServerSideInput;
  int                 nReturnCode;
  protected Socket    ServerSocket = null;
  protected Vector    serverResponse = new Vector(1);
   
  public Ftp(String strHost, int iPort, String strUserId, String strPassword) throws IOException
  {
         m_strUserID = strUserId;
      m_strPassword = strPassword;
      openServer(strHost, iPort);
  }
   
    // --------------------------------------------------------------------------|
    // Use standard FTP port when port not specified.
    // --------------------------------------------------------------------------|
  public Ftp(String strHost, String strUserId, String strPassword) throws IOException
  {
         m_strUserID = strUserId;
      m_strPassword = strPassword;
      openServer(strHost, FTP_PORT);
  }
   
  public Ftp(String strHost, int iPort) throws IOException
  {
      openServer(strHost, iPort);
  }
   
    // --------------------------------------------------------------------------|
    // Use standard FTP port when port not specified. Assume Anonymous login
    // when no userid or password are specified.
    // --------------------------------------------------------------------------|
  public Ftp(String strHost) throws IOException
  {
      m_strHost = strHost;
      openServer(strHost, FTP_PORT);
  }
   
    // -------------------------------------------------------------------------|
    //      APPEND (with create) (APPE)
    //
    //         This command causes the server-DTP to accept the data
    //         transferred via the data connection and to store the data in
    //         a file at the server site.  If the file specified in the
    //         pathname exists at the server site, then the data shall be
    //         appended to that file; otherwise the file specified in the
    //         pathname shall be created at the server site.
    // -------------------------------------------------------------------------|
    // Append to an ascii file.
  public BufferedWriter appendAscii(String strFileName) throws IOException
  {
      Socket s = openDataConnection("APPE " + strFileName);
      return new BufferedWriter(new OutputStreamWriter(s.getOutputStream()),4096);
  }
    // Append to a binary file.
  public BufferedOutputStream appendBinary(String strFileName) throws IOException
  {
      Socket s = openDataConnection("APPE " + strFileName);
      return new BufferedOutputStream(s.getOutputStream());
  }
   
    // -------------------------------------------------------------------------|
    //      RETRIEVE (RETR)
    //
    //         This command causes the server-DTP to transfer a copy of the
    //         file, specified in the pathname, to the server- or user-DTP
    //         at the other end of the data connection.  The status and
    //         contents of the file at the server site shall be unaffected.
    // -------------------------------------------------------------------------|
    // Retrieve Ascii File
  public BufferedReader getAsciiFile(String strFileName) throws IOException
  {
      Socket  s = null;
      try {
          s = openDataConnection("RETR " + strFileName);
      } catch (FileNotFoundException fileException) {fileException.printStackTrace();}
      return new BufferedReader( new InputStreamReader(s.getInputStream()));
  }
    // Retrieve Binary File
  public BufferedInputStream getBinary(String strFileName) throws IOException
  {
      Socket  s = null;
      try {
          s = openDataConnection("RETR " + strFileName);
      } catch (FileNotFoundException fileException) {fileException.printStackTrace();}
      return new BufferedInputStream(s.getInputStream());
  }
   
    // -------------------------------------------------------------------------|
    //      LIST (LIST)
    //
    //         This command causes a list to be sent from the server to the
    //         passive DTP.  If the pathname specifies a directory or other
    //         group of files, the server should transfer a list of files
    //         in the specified directory.  If the pathname specifies a
    //         file then the server should send current information on the
    //         file.  A null argument implies the user's current working or
    //         default directory.  The data transfer is over the data
    //         connection in type ASCII or type EBCDIC.
    // -------------------------------------------------------------------------|
  public BufferedReader list() throws IOException
  {
      Socket s = openDataConnection("LIST");
      return new BufferedReader( new InputStreamReader(s.getInputStream()));
  }
   
    // -------------------------------------------------------------------------|
    //      CHANGE WORKING DIRECTORY (CWD)
    //
    //         This command allows the user to work with a different
    //         directory or dataset for file storage or retrieval without
    //         altering his login or accounting information.  Transfer
    //         parameters are similarly unchanged.  The argument is a
    //         pathname specifying a directory or other system dependent
    //         file group designator.
    // -------------------------------------------------------------------------|
  public void cd(String remoteDirectory) throws IOException
  {
      sendCurrentCommandCheck("CWD " + remoteDirectory);
  }
   
    // -------------------------------------------------------------------------|
    //      NAME LIST (NLST)
    //
    //         This command causes a directory listing to be sent from
    //         server to user site.  The pathname should specify a
    //         directory or other system-specific file group descriptor; a
    //         null argument implies the current directory.  The server
    //         will return a stream of names of files and no other
    //         information.  The data will be transferred in ASCII or
    //         EBCDIC type over the data connection as valid pathname
    //         strings separated by <CRLF> or <NL>.  (Again the user must
    //        ensure that the TYPE is correct.)  This command is intended
    //         to return information that can be used by a program to
    //         further process the files automatically.  For example, in
    //         the implementation of a "multiple get" function.
    // -------------------------------------------------------------------------|
  public BufferedReader nlist() throws IOException
  {
      Socket s = openDataConnection("NLST");
      return new BufferedReader( new InputStreamReader(s.getInputStream()));
  }
   
    // -------------------------------------------------------------------------|
    //      RENAME FROM (RNFR)
    //
    //         This command specifies the old pathname of the file which is
    //         to be renamed.  This command must be immediately followed by
    //         a "rename to" command specifying the new file pathname.
    // -------------------------------------------------------------------------|
  public void rename(String oldFile, String newFile) throws IOException
  {
         sendCurrentCommandCheck("RNFR " + oldFile);
         sendCurrentCommandCheck("RNTO " + newFile);
  }
   
    // -------------------------------------------------------------------------|
    //      STORE (STOR)
    //
    //         This command causes the server-DTP to accept the data
    //         transferred via the data connection and to store the data as
    //         a file at the server site.  If the file specified in the
    //         pathname exists at the server site, then its contents shall
    //         be replaced by the data being transferred.  A new file is
    //         created at the server site if the file specified in the
    //         pathname does not already exist.
    // -------------------------------------------------------------------------|
    // Store in Ascii format
  public BufferedWriter putAscii(String strFileName) throws IOException
  {
      Socket s = openDataConnection("STOR " + strFileName);
      return new BufferedWriter(new OutputStreamWriter(s.getOutputStream()),4096);
  }
  // Store in Binary format
  public BufferedOutputStream putBinary(String strFileName) throws IOException
  {
      Socket s = openDataConnection("STOR " + strFileName);
      return new BufferedOutputStream(s.getOutputStream());
  }
   
    // -------------------------------------------------------------------------|
    //      TYPE (TYPE)
    //
    //         The argument specifies the representation type as described
    //         in the Section on Data Representation and Storage.  Several
    //         types take a second parameter.  The first parameter is
    //         denoted by a single Telnet character, as is the second
    //         Format parameter for ASCII and EBCDIC; the second parameter
    //         for local byte is a decimal integer to indicate Bytesize.
    //         The parameters are separated by a <SP> (Space, ASCII code
    //         32).
    //
    //         The following codes are assigned for type:
    //
    //                      \    /
    //            A - ASCII |    | N - Non-print
    //                      |-><-| T - Telnet format effectors
    //            E - EBCDIC|    | C - Carriage Control (ASA)
    //                      /    \
    //            I - Image
    //
    //            L <byte size> - Local byte Byte size
    // -------------------------------------------------------------------------|
    // Set user specifed mode.
    public void setType(String strType) throws IOException
  {
         sendCurrentCommandCheck("TYPE " + strType);
  }
  // Set binary mode.
  public void setBinaryMode() throws IOException
  {
      sendCurrentCommandCheck("TYPE I");
      m_bBinaryMode = true;
  }
  // Set ascii mode
  public void setAsciiMode() throws IOException
  {
      sendCurrentCommandCheck("TYPE A");
      m_bBinaryMode = false;
  }
  // Set ebcdic mode, probably don't need to but what the heck.
  public void setEbcdic() throws IOException
  {
      sendCurrentCommandCheck("TYPE E");
      m_bBinaryMode = true;
  }
   
    // -------------------------------------------------------------------------|
    //      SITE PARAMETERS (SITE)
    //
    //         This command is used by the server to provide services
    //         specific to his system that are essential to file transfer
    //         but not sufficiently universal to be included as commands in
    //         the protocol.  The nature of these services and the
    //         specification of their syntax can be stated in a reply to
    //         the HELP SITE command.
    // -------------------------------------------------------------------------|
  public void site(String strParms) throws IOException
  {
         sendCurrentCommandCheck("SITE "+ strParms);
  }
   
    // -------------------------------------------------------------------------|
    //      CHANGE TO PARENT DIRECTORY (CDUP)
    //
    //         This command is a special case of CWD, and is included to
    //         simplify the implementation of programs for transferring
    //         directory trees between operating systems having different
    // -------------------------------------------------------------------------|
  public void cdup() throws IOException {
      sendCurrentCommandCheck("CDUP");
  }
   
    // -------------------------------------------------------------------------|
    //
    //      ABORT (ABOR)
    //
    //         This command tells the server to abort the previous FTP
    //         service command and any associated transfer of data.  The
    //         abort command may require "special action", as discussed in
    //         the Section on FTP Commands, to force recognition by the
    //         server.  No action is to be taken if the previous command
    //         has been completed (including data transfer).  The control
    //         connection is not to be closed by the server, but the data
    //         connection must be closed.
    // -------------------------------------------------------------------------|
  public void abort() throws IOException
  {
      sendCurrentCommandCheck("ABOR");
  }
   
    // -------------------------------------------------------------------------|
    //
    //      MAKE DIRECTORY (MKD)
    //
    //         This command causes the directory specified in the pathname
    //         to be created as a directory (if the pathname is absolute)
    //         or as a subdirectory of the current working directory (if
    //         the pathname is relative).
    // -------------------------------------------------------------------------|
  public void mkdir(String strTemp) throws IOException
  {
      sendCurrentCommandCheck("MKD " + strTemp);
  }
   
    // -------------------------------------------------------------------------|
    //
    //      DELETE (DELE)
    //
    //         This command causes the file specified in the pathname to be
    //         deleted at the server site.  If an extra level of protection
    //         is desired (such as the query, "Do you really wish to
    //         delete?"), it should be provided by the user-FTP process.
    // -------------------------------------------------------------------------|
  public void delete(String strTemp) throws IOException
  {
      sendCurrentCommandCheck("DELE " + strTemp);
  }
   
    // -------------------------------------------------------------------------|
    //      PRINT WORKING DIRECTORY (PWD)
    //
    //         This command causes the name of the current working
    //         directory to be returned in the reply.  See Appendix II.
    // -------------------------------------------------------------------------|
  public void pwd() throws IOException
  {
      sendCurrentCommandCheck("PWD");
  }
   
    // -------------------------------------------------------------------------|
    //      SYSTEM (SYST)
    //
    //         This command is used to find out the type of operating
    //         system at the server.  The reply shall have as its first
    //         word one of the system names listed in the current version
    //         of the Assigned Numbers document.
    // -------------------------------------------------------------------------|
  public void syst() throws IOException
  {
      sendCurrentCommandCheck("SYST");
  }
   
    // -------------------------------------------------------------------------|
    //      REMOVE DIRECTORY (RMD)
    //
    //         This command causes the directory specified in the pathname
    //         to be removed as a directory (if the pathname is absolute)
    //         or as a subdirectory of the current working directory (if
    //         the pathname is relative).
    // -------------------------------------------------------------------------|
  public void rmdir(String strTemp) throws IOException
  {
      sendCurrentCommandCheck("RMD " + strTemp);
  }
   
    // -------------------------------------------------------------------------|
    // This method will retrieve an Ascii text file from a remote.
    //
    // Parms: strFileName     Full path to the Ascii text file on the remote host.
    // -------------------------------------------------------------------------|
   
    // -------------------------------------------------------------------------|
    //      PASSIVE (PASV)
    //
    //         This command requests the server-DTP to "listen" on a data
    //         port (which is not its default data port) and to wait for a
    //         connection rather than initiate one upon receipt of a
    //         transfer command.  The response to this command includes the
    //         host and port address this server is listening on.
    // -------------------------------------------------------------------------|
  public void setPassiveMode(boolean mode) {
         m_bPassiveMode = mode;
    }
   
    // -------------------------------------------------------------------------|
    // Parse the remote host response.
    // -------------------------------------------------------------------------|
  public int readServerResponse() throws IOException {
         
      int             iTemp;
      int             continuingCode = -1;
      int             iCurrnetCode = -1;
      StringBuffer    replyBuf = new StringBuffer(32);
      String          strResponse;
         
      try{
              while (true) {
                   
                   while ((iTemp = m_ServerSideInput.read()) != -1) {
                       
                        if (iTemp == '\r') {
                             if ((iTemp = m_ServerSideInput.read()) != '\n')
                                  replyBuf.append('\r');
                        }
                        replyBuf.append((char)iTemp);
                        if (iTemp == '\n')
                             break;
                   }
                   
                   
                   strResponse = replyBuf.toString();
                   replyBuf.setLength(0);
                   
                   try {
                        iCurrnetCode = Integer.parseInt(strResponse.substring(0, 3));
                   } catch (NumberFormatException e) {
                        iCurrnetCode = -1;
                   } catch (StringIndexOutOfBoundsException e) {
                       
                        continue;
                   }
                   serverResponse.addElement(strResponse);
                   if (continuingCode != -1) {
                        if (iCurrnetCode != continuingCode ||
                             (strResponse.length() >= 4 && strResponse.charAt(3) == '-')) {
                             continue;
                        } else {
                             continuingCode = -1;
                             break;
                        }
                   } else if (strResponse.length() >= 4 && strResponse.charAt(3) == '-') {
                        continuingCode = iCurrnetCode;
                        continue;
                   } else {
                        break;
                   }
              }
      }catch(Exception e){e.printStackTrace();}
      return nReturnCode = iCurrnetCode;
  }
   
  public String receiveResponse() {
      String strTemp = new String();
      for(int i = 0;i < serverResponse.size();i++) {
              strTemp += serverResponse.elementAt(i);
      }
      serverResponse = new Vector(1);
      return strTemp;
  }
   
  public String receiveResponseWithNoReset() {
      String s = new String();
      for(int i = 0;i < serverResponse.size();i++) {
              s+=serverResponse.elementAt(i);
      }
      return s;
  }
   
  public void sendServer(String strCommand)
  {
      m_ServerSideOutput.println(strCommand);
         
  }
   
  public boolean serverConnectionOpen()
  {
      return ServerSocket != null;
  }
   
    // -------------------------------------------------------------------------|
    // -------------------------------------------------------------------------|
  protected int sendCurrentCommand(String strCommand) throws IOException
  {
      m_strCurrentCommand = strCommand;
         
      int iReply;
         
      if (m_bReplyPending) {
             
          if (readResponse() == FTP_ERROR)
              System.out.print("Error reading current pending reply\n");
      }
      m_bReplyPending = false;
      do {
          sendServer(strCommand);
          iReply = readResponse();
             
      } while (iReply == FTP_TRY_AGAIN);
      return iReply;
  }
   
    // -------------------------------------------------------------------------|
    // Check the current command for validity.
    // -------------------------------------------------------------------------|
  protected void sendCurrentCommandCheck(String strCommand) throws IOException
  {
         
      if (sendCurrentCommand(strCommand) != FTP_SUCCESSFULL) {
          throw new FtpProtocolException(strCommand);
      }
  }
   
    // -------------------------------------------------------------------------|
    //      LOGOUT (QUIT)
    //
    //         This command terminates a USER and if file transfer is not
    //         in progress, the server closes the control connection.  If
    //         file transfer is in progress, the connection will remain
    //         open for result response and the server will then close it.
    //         If the user-process is transferring files for several USERs
    //         but does not wish to close and then reopen connections for
    //         each, then the REIN command should be used instead of QUIT.
    //
    //         An unexpected close on the control connection will cause the
    //         server to take the effective action of an abort (ABOR) and a
    //         logout (QUIT).
    // -------------------------------------------------------------------------|
  public void exitServer() throws IOException
  {
      if (serverConnectionOpen())
      {
          sendCurrentCommand("QUIT");
          if (! serverConnectionOpen())
          {
                   return;
          }
          ServerSocket.close();
          ServerSocket                = null;
          m_ServerSideInput      = null;
          m_ServerSideOutput      = null;
      }
  }
   
    // -------------------------------------------------------------------------|
    // Parse remote host response for errors.
    //
    //   Reply Codes by Function Groups
    //
    //      110 Restart marker reply.
    //          In this case, the text is exact and not left to the
    //          particular implementation; it must read:
    //               MARK yyyy = mmmm
    //          Where yyyy is User-process data stream marker, and mmmm
    //          server's equivalent marker (note the spaces between markers
    //          and "=").
    //      120 Service ready in nnn minutes.
    //      125 Data connection already open; transfer starting.
    //      150 File status okay; about to open data connection.
    //      200 Command okay.
    //      202 Command not implemented, superfluous at this site.
    //      211 System status, or system help reply.
    //      212 Directory status.
    //      213 File status.
    //      214 Help message.
    //          On how to use the server or the meaning of a particular
    //          non-standard command.  This reply is useful only to the
    //          human user.
    //      215 NAME system type.
    //          Where NAME is an official system name from the list in the
    //          Assigned Numbers document.
    //      220 Service ready for new user.
    //      221 Service closing control connection.
    //          Logged out if appropriate.
    //      225 Data connection open; no transfer in progress.
    //      226 Closing data connection.
    //          Requested file action successful (for example, file
    //          transfer or file abort).
    //      227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
    //      230 User logged in, proceed.
    //      250 Requested file action okay, completed.
    //      257 "PATHNAME" created.
    //
    //      331 User name okay, need password.
    //      332 Need account for login.
    //      350 Requested file action pending further information.
    //
    //      421 Service not available, closing control connection.
    //          This may be a reply to any command if the service knows it
    //          must shut down.
    //      425 Can't open data connection.
    //      426 Connection closed; transfer aborted.
    //      450 Requested file action not taken.
    //          File unavailable (e.g., file busy).
    //      451 Requested action aborted: local error in processing.
    //      452 Requested action not taken.
    //          Insufficient storage space in system.
    //      500 Syntax error, command unrecognized.
    //          This may include errors such as command line too long.
    //      501 Syntax error in parameters or arguments.
    //      502 Command not implemented.
    //      503 Bad sequence of commands.
    //      504 Command not implemented for that parameter.
    //      530 Not logged in.
    //      532 Need account for storing files.
    //      550 Requested action not taken.
    //          File unavailable (e.g., file not found, no access).
    //      551 Requested action aborted: page type unknown.
    //      552 Requested file action aborted.
    //          Exceeded storage allocation (for current directory or
    //          dataset).
    //      553 Requested action not taken.
    //          File name not allowed.
    // -------------------------------------------------------------------------|
  protected int readResponse() throws IOException
  {
      nReturnCode = readServerResponse();
         
      switch (nReturnCode / 100)
      {
         case 1:
          m_bReplyPending = true;
             
      case 2: // Do nothing, pass through.
             
      case 3:
             
          return FTP_SUCCESSFULL;
             
      case 4:
             
              if (nReturnCode == 421)
          {
                   throw new FtpConnectException("Connection shut down");
          }
              if (nReturnCode == 425)
          {
                   throw new FtpConnectException("Can't open data connection.");
          }
              if (nReturnCode == 426)
          {
                   throw new FtpConnectException("Connection closed; transfer aborted.");
          }
              if (nReturnCode == 421)
          {
                   throw new FtpConnectException("Connection shut down");
          }
              if (nReturnCode == 421)
          {
                   throw new FtpConnectException("Connection shut down");
          }
          return FTP_ERROR;
             
      case 5:
          if (nReturnCode == 530)
          {
              if (m_strUserID == null)
              {
                        throw new FtpLoginException("No userid found");
                   }
              else if (m_strPassword == null) {

                        throw new FtpLoginException("No password was provided");
                   }

              return FTP_ERROR;
          }

          if (nReturnCode == 550)
          {
              if (!m_strCurrentCommand.startsWith("PASS"))

                        throw new FileNotFoundException(m_strCurrentCommand);
              else

                        throw new FtpLoginException("Bad password!");
          }
          if (nReturnCode == 532)
          {
                   throw new FtpLoginException("No account defined for user");
          }
      }

      return FTP_ERROR;
  }

    // -------------------------------------------------------------------------|
    //
    // -------------------------------------------------------------------------|
    protected Socket openDataConnection(String strCommand) throws IOException
    {

         ServerSocket portSocket = null;
         int          iPort = 0;
         String       portCmd;
         int          shift;
         InetAddress  myAddress = InetAddress.getLocalHost();
         byte         addr[] = myAddress.getAddress();
         String       ipaddress;
         IOException  e;

         if (this.m_bPassiveMode) {

              try {

                   receiveResponse();

                   if (sendCurrentCommand("PASV") == FTP_ERROR) {

                        e = new FtpProtocolException("PASV");
                        throw e;
                   }

                   String reply = receiveResponseWithNoReset();
                   reply = reply.substring(reply.lastIndexOf("(")+1,reply.lastIndexOf(")"));
                   StringTokenizer st = new StringTokenizer(reply, ",");
                   String[] nums = new String[6];
                   int i = 0;

                   while(st.hasMoreElements()) {

                        try
                        {
                             nums[i] = st.nextToken();
                             i++;
                        }
                        catch(Exception all) {

                             all.printStackTrace();
                        }
                   }

                   // Format ip address
                   ipaddress = nums[0]+"."+nums[1]+"."+nums[2]+"."+nums[3];

                   try
                   {
                        int firstbits = Integer.parseInt(nums[4]) << 8;
                        int lastbits = Integer.parseInt(nums[5]);
                        iPort = firstbits + lastbits;
                   }
                   catch(Exception b) {

                        b.printStackTrace();
                   }

                   if((ipaddress != null) && (iPort != 0))
                   {
                        m_Socket = new Socket(ipaddress, iPort);}

                   else {

                        e = new FtpProtocolException("PASV");
                        throw e;
                   }

                   if (sendCurrentCommand(strCommand) == FTP_ERROR)
                   {
                        e = new FtpProtocolException(strCommand);
                        throw e;
                   }

              }
              catch (FtpProtocolException fpe) {

                   portCmd = "PORT ";

                   for (int i = 0; i < addr.length; i++) {

                        portCmd = portCmd + (addr[i] & 0xFF) + ",";
                   }

                   try
                   {

                        portSocket = new ServerSocket(20000);

                        portCmd = portCmd + ((portSocket.getLocalPort() >>> 8) & 0xff) + ","
                             + (portSocket.getLocalPort() & 0xff);

                        if (sendCurrentCommand(portCmd) == FTP_ERROR)
                        {
                             e = new FtpProtocolException("PORT");
                             throw e;
                        }

                        if (sendCurrentCommand(strCommand) == FTP_ERROR)
                        {
                             e = new FtpProtocolException(strCommand);
                             throw e;
                        }

                        m_Socket = portSocket.accept();
                   }
                   finally {

                        if(portSocket != null)
                             portSocket.close();
                   }

                   m_Socket = portSocket.accept();
                   portSocket.close();

              }
         }
         else {

              portCmd = "PORT ";

              for (int i = 0; i < addr.length; i++) {
                   portCmd = portCmd + (addr[i] & 0xFF) + ",";
              }

              try {

                   portSocket = new ServerSocket(20000);

                   portCmd = portCmd + ((portSocket.getLocalPort() >>> 8) & 0xff) + ","
                        + (portSocket.getLocalPort() & 0xff);
                   if (sendCurrentCommand(portCmd) == FTP_ERROR)
                   {
                        e = new FtpProtocolException("PORT");
                        throw e;
                   }

                   if (sendCurrentCommand(strCommand) == FTP_ERROR) {
                        e = new FtpProtocolException(strCommand);
                        throw e;
                   }
                   m_Socket = portSocket.accept();
              }
              finally {

                   if(portSocket != null)
                        portSocket.close();
              }

              m_Socket = portSocket.accept();
              portSocket.close();
         }

         return m_Socket;
  }


    // -------------------------------------------------------------------------|
    // Open up a connection with the remote host. Define the Output buffer
    // and input buffers.
    // -------------------------------------------------------------------------|
  public void openServer(String strHost) throws IOException, UnknownHostException {
      int iPort = FTP_PORT;
      if (ServerSocket != null)
          exitServer();
      ServerSocket = new Socket(strHost, FTP_PORT);
      m_ServerSideOutput = new PrintWriter(new BufferedOutputStream(ServerSocket.getOutputStream()),true);
      m_ServerSideInput = new BufferedInputStream(ServerSocket.getInputStream());
  }

    // -------------------------------------------------------------------------|
    // Login in to the remote host.
    // -------------------------------------------------------------------------|
    public void login(String strUser) throws IOException {

         if (!serverConnectionOpen())
              throw new FtpLoginException("Currently not connected to host");
         this.m_strUserID = strUser;
         if (sendCurrentCommand("USER " + strUser) == FTP_ERROR)
          throw new FtpLoginException("Error: Invalid Username.\n");
  }

    // -------------------------------------------------------------------------|
    // Login in to the remote host.
    // -------------------------------------------------------------------------|
  public void login(String strUser, String strPassword) throws IOException {

      if (!serverConnectionOpen())
          throw new FtpLoginException("Error: not connected to host.\n");
      this.m_strUserID = strUser;
      this.m_strPassword = strPassword;
      if (sendCurrentCommand("USER " + strUser) == FTP_ERROR)
          throw new FtpLoginException("Error: User not found.\n");
      if (m_strPassword != null && sendCurrentCommand("PASS " + strPassword) == FTP_ERROR)
          throw new FtpLoginException("Error: Bad Password.\n");
  }
    // -------------------------------------------------------------------------|
    // Login in to the remote host.
    // -------------------------------------------------------------------------|
  public void login() throws IOException {

      if (!serverConnectionOpen())
          throw new FtpLoginException("Error: not connected to host.\n");

      if(this.m_strUserID == null)
        this.m_strUserID = "anonymous";

      if(this.m_strPassword == null)
        this.m_strPassword = "tempest@isrglobal.com";

      if (sendCurrentCommand("USER " + this.m_strUserID) == FTP_ERROR)
          throw new FtpLoginException("Error: User not found.\n");
      if (m_strPassword != null && sendCurrentCommand("PASS " + this.m_strPassword) == FTP_ERROR)
          throw new FtpLoginException("Error: Bad Password.\n");
  }

    // -------------------------------------------------------------------------|
    // Open socket connect to the remote host.
    // -------------------------------------------------------------------------|
  public void openServer(String strHost, int iPort) throws IOException, UnknownHostException {
      if (ServerSocket != null)
          exitServer();
      ServerSocket = new Socket(strHost, iPort);

      m_ServerSideOutput = new PrintWriter(new BufferedOutputStream(ServerSocket.getOutputStream()),
              true);
      m_ServerSideInput = new BufferedInputStream(ServerSocket.getInputStream());

      if (readResponse() == FTP_ERROR)
          throw new FtpConnectException("Welcome message");
  }


    // -------------------------------------------------------------------------|
    // Login to remote host and retreive the indicated file from the
    // remote host.
    // -------------------------------------------------------------------------|
  public void GetAsciiFile(String strFileName) throws IOException
  {
         System.out.print(receiveResponse());

         setPassiveMode(true);

         //////////////////////////////////////////////////////////////////////////

         setAsciiMode();
         System.out.println(m_strCurrentCommand);
         System.out.print(receiveResponse());
         BufferedReader fInputFile = getAsciiFile(strFileName);
         System.out.println(m_strCurrentCommand);
         System.out.print(receiveResponse());
         PrintWriter fOutPutFile = new PrintWriter(new BufferedWriter(new FileWriter(strFileName)));
         int i;
         char c[] = new char[4096];
         while ((i = fInputFile.read(c)) != -1)
              fOutPutFile.write(c,0,i);
         fInputFile.close();
         fOutPutFile.close();

         System.out.print(receiveResponse());

  }
    // -------------------------------------------------------------------------|
    // Login to remote host and retreive the indicated file from the
    // remote host.
    // -------------------------------------------------------------------------|
  public void GetBinaryFile(String strFileName) throws IOException
  {
         System.out.print(receiveResponse());

         setPassiveMode(true);

         //////////////////////////////////////////////////////////////////////////
         setBinaryMode();
         System.out.println(m_strCurrentCommand);
         System.out.print(receiveResponse());
         BufferedInputStream fInputFile = getBinary(strFileName);

         System.out.println(m_strCurrentCommand);
         System.out.print(receiveResponse());
         BufferedOutputStream fOutputFile = new BufferedOutputStream(new FileOutputStream(strFileName));
         int i;
         byte b[] = new byte[4096];
         while ((i = fInputFile.read(b)) != -1)
              fOutputFile.write(b,0,i);
         fInputFile.close();
         fOutputFile.close();

         System.out.print(receiveResponse());

  }
    // -------------------------------------------------------------------------|
    // Login to remote host and retreive the indicated file from the
    // remote host.
    // -------------------------------------------------------------------------|
  public void SendBinaryFile(String strFileName) throws IOException
  {

         System.out.print(receiveResponse());

         setPassiveMode(true);

         //////////////////////////////////////////////////////////////////////////

         String localFile = strFileName;
         setBinaryMode();
         System.out.println(m_strCurrentCommand);
         BufferedOutputStream fOutputFile = putBinary(localFile);
         System.out.println(m_strCurrentCommand);
         System.out.print(receiveResponse());
         BufferedInputStream fInputFile = new BufferedInputStream(new FileInputStream(localFile));
         int j;
         byte b[] = new byte[1024];

         while ((j = fInputFile.read(b)) != -1)
              fOutputFile.write(b,0,j);

         fInputFile.close();
         fOutputFile.flush();
         fOutputFile.close();

         System.out.print(receiveResponse());

         // Shut down
         exitServer();
         System.out.println(m_strCurrentCommand);
         System.out.print(receiveResponse());


  }
    // -------------------------------------------------------------------------|
    // Login to remote host and retreive the indicated file from the
    // remote host.
    // -------------------------------------------------------------------------|
  public void SendAsciiFile(String strFileName) throws IOException
  {

         System.out.print(receiveResponse());

         setPassiveMode(true);

         //////////////////////////////////////////////////////////////////////////

         String strLocalFile = strFileName;
         setAsciiMode();
         System.out.println(m_strCurrentCommand);
         BufferedWriter fOutputFile = putAscii(strLocalFile);
         System.out.println(m_strCurrentCommand);
         System.out.print(receiveResponse());
         BufferedInputStream fInputFile = new BufferedInputStream(new FileInputStream(strLocalFile));

         int j;

         while ((j = fInputFile.read()) != -1)
         {
              fOutputFile.write(j);
         }
         fInputFile.close();
         fOutputFile.flush();
         fOutputFile.close();

         System.out.print(receiveResponse());

         // Shut down
         exitServer();
         System.out.println(m_strCurrentCommand);
         System.out.print(receiveResponse());
  }

  // ------------------------------------------------------------------------|
  // For testing purposes.
  // ------------------------------------------------------------------------|
  public static void main (String args []) throws IOException
  {
         // Sample to send an ascii file.
        Ftp clsFtp = new Ftp("203.129.237.74");
            clsFtp.login("root","melstar");
         //clsFtp.SendAsciiFile("test.txt");

         // Sample to receive a binary file.
//          Ftp clsFtp = new Ftp("203.129.237.74","root","melstar");
 //        Ftp clsFtp = new Ftp("www.cisco.com");
 // clsFtp.login();
 // clsFtp.setPassiveMode(true);
    clsFtp.cd("opt");
    clsFtp.cd("test");
//    clsFtp.cd("catalyst");
//    clsFtp.cd("1900-standard");
//    String strPath = "pub/lan/catalyst/1900-standard/cat1900A.9.00.04.bin";
  //File flFileName = new File("pub/lan/catalyst/1900-standard/cat1900A.9.00.04.bin\r");
  //String strTest =  flFileName.getParent();
  //String strTest2 = flFileName.getName();
  //String strParentDir = flFileName.getParent();
  //if(strParentDir != null)
 // clsFtp.cd("pub/lan/catalyst/1900-standard");

  //String strFileName =  "pub/lan/catalyst/1900-standard/cat1900A.9.00.04.bin ";
  String strFileName =  "alphabets.txt";
  System.out.print(strFileName);
  clsFtp.GetBinaryFile(strFileName);

         // ----------------------------------------------------------------------|
         // Sample, retrieve a directory listing from the host
         // ----------------------------------------------------------------------|
        /*
         Ftp clsFtp = new Ftp("203.129.237.74");
         clsFtp.login("root","melstar");
         clsFtp.setPassiveMode(true);
         try {
         BufferedReader myBuffer = clsFtp.list();
         BufferedOutputStream fOutputFile =
         new BufferedOutputStream(new FileOutputStream("testfile.txt"));
         int j;
         char c[] = new char[1024];
         while((j = myBuffer.read()) != -1)
         {
         fOutputFile.write(j);
         }
         }
         catch (Exception e) {
         
           System.out.println("Failed to list directory directory");
           }
           
         */
         // ----------------------------------------------------------------------|
         // Sample, create a directory on the remote host.
         // ----------------------------------------------------------------------|
        /*
         Ftp clsFtp = new Ftp("203.129.237.74");
         clsFtp.login("root","melstar");
         clsFtp.setPassiveMode(true);
         
           try
           {
           clsFtp.mkdir("Talon");
           }
           catch (Exception e) {
           
              System.out.println("Failed to create directory");
              }
         */
         
         // ----------------------------------------------------------------------|
         // Sample, remove a directory on the remote host.
         // ----------------------------------------------------------------------|
         /*
         Ftp clsFtp = new Ftp("203.129.237.74");
         clsFtp.login("root","melstar");
         clsFtp.setPassiveMode(true);
         
           try
           {
           clsFtp.rmdir("Talon");
           }
           catch (Exception e) {
           
              System.out.println("Failed to delete directory");
ckdkdkdkd               }
         */
         // ----------------------------------------------------------------------|
         // Sample, change directory on the remote host.
         // ----------------------------------------------------------------------|
         /*
         Ftp clsFtp = new Ftp("203.129.237.74");
         clsFtp.login("root","melstar");
         clsFtp.setPassiveMode(true);
         
           try
           {
           clsFtp.cd("opt/test");
              clsFtp.pwd();
           }
           catch (Exception e) {
           
              System.out.println("Failed to create directory");
              }
         */
         
    }
}

class FtpProtocolException extends IOException {
  FtpProtocolException(String s) {
      super(s);
  }
}
class FtpConnectException extends FtpProtocolException {
  FtpConnectException(String s) {
      super(s);
  }
}

class FtpLoginException extends FtpProtocolException {
  FtpLoginException(String s) {
      super(s);
  }
}
0
 
LVL 3

Expert Comment

by:dnoelpp
ID: 6194540
Rajendra, where did you copy the code from?
0
 
LVL 1

Expert Comment

by:rajendra_rathod
ID: 6194857
Hi,

That u have to find out.
0
 
LVL 3

Expert Comment

by:dnoelpp
ID: 6194884
Do you know what I call this?

CHEATING!

I think the captain would prefer to know more about the origin of the code. Imagine there was a copyright to it and you removed it. Then the captain will get into trouble, not you.

Thanks for listening.
0
 
LVL 1

Expert Comment

by:rajendra_rathod
ID: 6195020
Hi,

That u have to find out.
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 3

Expert Comment

by:dnoelpp
ID: 6195034
Hey, Rajendra, please give a sensible answer, if you prefer to answer at all. I might report you to Community Support...
0
 

Author Comment

by:CaptainKirk
ID: 6203268
This is the "Captain",

Thankyou Rajendra for the code, however, I have to agree with dnoelpp.  I will need to know the origin of the code in case of CopyRight.  If you do not wish to disclose the source I will understand.

Thanks again,

0
 
LVL 1

Expert Comment

by:rajendra_rathod
ID: 6205128
Hi,

There is no CopyRight for the above code. You will find many sites which gives u the free code. It is your skill How u find out and implement according to your need?



0
 
LVL 3

Accepted Solution

by:
dnoelpp earned 300 total points
ID: 6205306
This is not just a question of skill how to find good examples. It is a question of fairness, too. I have the feeling the writer of the Ftp class won't be very happy about you copying the code and not even bothering naming him as the writer.

I surely would feel this way.

*** ***

By the way, Captain, I have a link for a free library: NetComponents. They contain a FTP client, too:

http://www.savarese.org/oro/products/NetComponents.html

This is the API of the Ftp class:

http://www.savarese.org/oro/developers/docs/NetComponents/api/com.oroinc.net.ftp.FTP.html
0
 

Author Comment

by:CaptainKirk
ID: 6225031
Thanks alot!
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now