Class FTP


  • public class FTP
    extends java.lang.Object
    This class implements the File Transfer Protocol.

    Note: if you're experiencing slowness in the server, try to disable the reverse-ip resolution in your FTP server: this will speedup everything.

    Check the sample RemoteExplorer. Here is an example code:
         ftp = new FTP(url, user, pass, cbLog);
         ftp.makeDir("tempdir");
         ftp.changeDir("tempdir");
         String textfile = "Viva Verinha!";
         ByteArrayStream bas = new ByteArrayStream(textfile.getBytes());
         ftp.sendFile(bas, "verinha.txt", false);
         String[] files = ftp.list("*.txt");
         if (files == null || files.length != 1)
            cbLog.add("Something went wrong in sending files...");
         ftp.rename("verinha.txt", "vivaverinha.txt");
         bas = new ByteArrayStream(50);
         ftp.receiveFile("vivaverinha.txt", bas);
         cbLog.add(new String(bas.getCopy()));
         ftp.delete("vivaverinha.txt");
         ftp.changeDir("..");
         ftp.removeDir("tempdir");
     
    You can use the CompressedByteArrayStream to transfer and receive big files to/from the server (check the class for more information and samples).

    To transfer a File to the server, all you have to do is:

         File f = new File("michelle.txt", File.READ_WRITE);
         ftp.sendFile(f, "michelle.txt", false); // last parameter depends on what you want to do
     
    It is currently impossible to transfer a whole PDBFile to/from the server. The solution for this would be to send each record in pieces, and store it in separate files in the server. Then a routine written in TotalCross in the server could reassemble the records into a new PDBFile. Here is an idea:
         // for the Client:
         // i assume that a ftp class is prepared to be used
         String name = "myPDBFile";
         PDBFile cat = new PDBFile(name + ".crtr.type", READ_WRITE);
         int n = cat.getRecordCount();
         for (int i = 0; i < n; i++)
         {
            if (!cat.setRecordPos(i))
               throw new RuntimeException("PDBFile is in use elsewhere!");
            else
               ftp.sendFile(cat, name + "#" + i, false);
         }
    
         // for the server
         String name = "myPDBFile";
         // for simplicity, I'll assume that the PDBFile does not exists
         byte[] buf = new byte[65536]; // in desktop this is possible
         PDBFile cat = new PDBFile(name + ".crtr.type", PDBFile.CREATE);
         for (int i = 0;; i++)
         {
            File f = new File(name + "#" + i, File.READ_WRITE);
            if (!f.exists())
               break; // no more records
            int size = f.getSize();
            f.readBytes(buf, 0, size);
            f.delete(); // could be also: f.close();
    
            cat.addRecord(size);
            cat.writeBytes(buf, 0, size);
         }
         cat.close();
     
    The example above can be easily changed to add support for compression.

    Here is a list of error codes that can thrown if an Exception occurs:

    Code Description
    100 Codes The requested action is being taken. Expect a reply before proceeding with a new command.
    110 Restart marker reply.
    120 Service ready in (n) minutes.
    125 Data connection already open, transfer starting.
    150 File status okay, about to open data connection.
    200 Codes The requested action has been successfully completed.
    200 Command okay.
    202 Command not implemented
    211 System status, or system help reply.
    212 Directory status.
    213 File status.
    214 Help message.
    215 NAME system type. (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 (file transfer, abort, etc.).
    227 Entering Passive Mode
    230 User logged in, proceed.
    250 Requested file action okay, completed.
    257 "PATHNAME" created.
    300 Codes The command has been accepted, but the requested action is being held pending receipt of further information.
    331 User name okay, need password.
    332 Need account for login.
    350 Requested file action pending further information.
    If you're using "list *.txt", try "list *.*" and filter localy.
    400 Codes The command was not accepted and the requested action did not take place.
    Tthe error condition is temporary, however, and the action may be requested again.
    421 Service not available, closing control connection. (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 Codes The command was not accepted and the requested action did not take place.
    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 User not logged in.
    532 Need account for storing files.
    550 Requested action not taken. File unavailable (e.g., file not found, no access).
    552 Requested file action aborted, storage allocation exceeded
    553 Requested action not taken. Illegal file name.
    Since:
    SuperWaba 5.6
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static interface  FTP.ProgressInformation
      Assign the progressInfo member to an instance of this interface to receive information of how many bytes were transfered.
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.lang.String ASCII
      Defines an ASCII transfer type.
      static java.lang.String BINARY
      Defines a BINARY transfer type.
      static int defaultOpenTimeout
      Default open timeout: 15 seconds.
      static int defaultPort
      Default port: 21.
      static int defaultReadTimeout
      Default read timeout: 5 seconds.
      static int defaultWriteTimeout
      Default write timeout: 5 seconds.
      static java.lang.String EBCDIC
      Defines an EBCDIC transfer type.
      static boolean log2console
      Set this to true to send the log to both the console and the combo.
      FTP.ProgressInformation progressInfo
      Assign the ProgressInformation member to receive information about the file transfer.
      int sendSleep
      This makes a sleep during the send of a file.
    • Constructor Summary

      Constructors 
      Constructor Description
      FTP​(java.lang.String url, java.lang.String user, java.lang.String pass)
      Opens a socket to the given URL, user, password and the default timeouts.
      FTP​(java.lang.String url, java.lang.String user, java.lang.String pass, int port)
      Opens a socket to the given URL, user, password, port and the default timeouts.
      FTP​(java.lang.String url, java.lang.String user, java.lang.String pass, int openTimeout, int readTimeout, int writeTimeout)
      Opens a socket to the given URL, user, password, and timeouts.
      FTP​(java.lang.String url, java.lang.String user, java.lang.String pass, int port, int openTimeout, int readTimeout, int writeTimeout, Control loggingControl)
      Opens a socket to the given URL, user, password, port, timeouts and logging control.
      FTP​(java.lang.String url, java.lang.String user, java.lang.String pass, int openTimeout, int readTimeout, int writeTimeout, Control loggingControl)
      Opens a socket to the given URL, user, password, timeouts and logging control
      FTP​(java.lang.String url, java.lang.String user, java.lang.String pass, Control loggingControl)
      Opens a socket to the given URL, user, password, logging control and the default timeouts.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void createDir​(java.lang.String pathName)
      Creates a directory at the server site.
      void delete​(java.lang.String pathName)
      Deletes the file specified at the server site.
      void forceClose()
      Closes the control connection without issuing any quit or abort command to the server.
      java.lang.String getCurrentDir()
      Returns the name of the current working directory.
      java.lang.String[] list​(java.lang.String pathName)
      List the contents on the specified pathname.
      java.lang.String[] listNames​(java.lang.String pathName)
      List the names of the files on the specified pathname.
      void noop()
      This command may help to keep the connection open.
      void quit()
      Sends a quit command to the server and closes the socket.
      int receiveFile​(java.lang.String pathName, Stream outputStream)
      Transfers a copy of the file specified in the pathname from the server.
      void removeDir​(java.lang.String pathName)
      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).
      void rename​(java.lang.String oldPathName, java.lang.String newPathName)
      Renames a file at the server site.
      int sendFile​(Stream inputStream, java.lang.String pathName)
      Sends a file to be stored at the server site.
      void setCurrentDir​(java.lang.String pathName)
      Changes the user's current working directory to the given one.
      void setLoggingControl​(Control c)
      Sets the control where the log will be displayed.
      void setPort​(java.lang.String port)
      The argument is a HOST-PORT specification for the data port to be used in data connection.
      void setType​(java.lang.String type)
      Sets the data representation type.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • defaultOpenTimeout

        public static final int defaultOpenTimeout
        Default open timeout: 15 seconds.
        See Also:
        Constant Field Values
      • defaultReadTimeout

        public static final int defaultReadTimeout
        Default read timeout: 5 seconds.
        See Also:
        Constant Field Values
      • defaultWriteTimeout

        public static final int defaultWriteTimeout
        Default write timeout: 5 seconds.
        See Also:
        Constant Field Values
      • progressInfo

        public FTP.ProgressInformation progressInfo
        Assign the ProgressInformation member to receive information about the file transfer. This way, you can show it in a ProgressBar.
        Since:
        TotalCross 1.14
      • sendSleep

        public int sendSleep
        This makes a sleep during the send of a file. Important: when using softick, you must set this to 500(ms) or more, or softick will starve to death.
      • log2console

        public static boolean log2console
        Set this to true to send the log to both the console and the combo.
        Since:
        SuperWaba 5.66
    • Method Detail

      • setCurrentDir

        public void setCurrentDir​(java.lang.String pathName)
                           throws FTPConnectionClosedException,
                                  IOException
        Changes the user's current working directory to the given one. 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.
        Parameters:
        pathName - Specifies a directory or other system dependent file group designator.
        Throws:
        FTPConnectionClosedException
        IOException
      • setPort

        public void setPort​(java.lang.String port)
                     throws FTPConnectionClosedException,
                            IOException
        The argument is a HOST-PORT specification for the data port to be used in data connection. There are defaults for both the user and server data ports, and under normal circumstances this command and its reply are not needed. If this command is used, the argument is the concatenation of a 32-bit internet host address and a 16-bit TCP port address. This address information is broken into 8-bit fields and the value of each field is transmitted as a decimal number (in character string representation). The fields are separated by commas. A port command would be:
         PORT h1,h2,h3,h4,p1,p2
         
        where h1 is the high order 8 bits of the internet host address.
        Parameters:
        port - port to be used in data connection
        Throws:
        java.lang.NullPointerException - if port is null.
        FTPConnectionClosedException
        IOException
      • createDir

        public void createDir​(java.lang.String pathName)
                       throws FTPConnectionClosedException,
                              IOException
        Creates a directory at the server site. 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).
        Parameters:
        pathName - Specifies the directory to be created.
        Throws:
        java.lang.NullPointerException - if pathName is null.
        FTPConnectionClosedException
        IOException
      • removeDir

        public void removeDir​(java.lang.String pathName)
                       throws FTPConnectionClosedException,
                              IOException
        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).
        Parameters:
        pathName - Specifies the directory to be removed.
        Throws:
        java.lang.NullPointerException - if pathName is null.
        FTPConnectionClosedException
        IOException
      • rename

        public void rename​(java.lang.String oldPathName,
                           java.lang.String newPathName)
                    throws FTPConnectionClosedException,
                           IOException
        Renames a file at the server site.
        Parameters:
        oldPathName - Old pathname of the file which is to be renamed.
        newPathName - New pathname of the file specified to be renamed.
        Throws:
        java.lang.NullPointerException - if any of the arguments, oldPathName and newPathName, is null.
        FTPConnectionClosedException
        IOException
      • sendFile

        public int sendFile​(Stream inputStream,
                            java.lang.String pathName)
                     throws FTPConnectionClosedException,
                            IOException
        Sends a file to be stored 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.
        Parameters:
        inputStream - The Stream from where the data will be read (using readBytes method)
        pathName - The name of the destination file in the server
        Returns:
        Returns the total bytes sent. Its up to the user to check if it was the desired amount.
        Throws:
        java.lang.NullPointerException - if any of the arguments, inputStream or pathName, is null.
        FTPConnectionClosedException
        IOException
      • receiveFile

        public int receiveFile​(java.lang.String pathName,
                               Stream outputStream)
                        throws FTPConnectionClosedException,
                               IOException
        Transfers a copy of the file specified in the pathname from the server. The status and contents of the file at the server site shall be unaffected.
        Parameters:
        pathName - Specifies the file to be retrieved.
        outputStream - The stream to where the file will be written.
        Returns:
        number of bytes read.
        Throws:
        java.lang.NullPointerException - if any of the arguments, pathName or outputStream, is null.
        FTPConnectionClosedException
        IOException
      • list

        public java.lang.String[] list​(java.lang.String pathName)
                                throws FTPConnectionClosedException,
                                       IOException
        List the contents on the specified pathname. This command causes a list to be sent from the server 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. (The user must ensure that the TYPE is appropriately ASCII or EBCDIC). Since the information on a file may vary widely from system to system, this information may be hard to use automatically in a program, but may be quite useful to a human user.
        Parameters:
        pathName - Specifies a directory, a group of files or a single file. A null value lists the user's current directory or the default directory.
        Returns:
        The contents of the given pathname in the server
        Throws:
        FTPConnectionClosedException
        IOException
      • listNames

        public java.lang.String[] listNames​(java.lang.String pathName)
                                     throws FTPConnectionClosedException,
                                            IOException
        List the names of the files on the specified pathname. 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 or . (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.
        Parameters:
        pathName - Specifies a directory or a file group descriptor. A null value implies the user's current directory.
        Returns:
        The files of the given pathname in the server
        Throws:
        FTPConnectionClosedException
        IOException
      • setLoggingControl

        public void setLoggingControl​(Control c)
        Sets the control where the log will be displayed. Only ComboBox and ListBox are allowed.
      • forceClose

        public void forceClose()
                        throws IOException
        Closes the control connection without issuing any quit or abort command to the server. Avoid using this method unless strictly necessary, use the quit method instead.
        Throws:
        IOException