Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Licensed to the Apache Software Foundation (ASF) under one or more
    * contributor license agreements.  See the NOTICE file distributed with
    * this work for additional information regarding copyright ownership.
    * The ASF licenses this file to You under the Apache License, Version 2.0
    * (the "License"); you may not use this file except in compliance with
    * the License.  You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  package org.apache.commons.net.ftp;
  import java.net.Socket;
  import java.util.HashMap;
  import java.util.HashSet;
  import java.util.Locale;
  import java.util.Random;
  import java.util.Set;
  
  import  org.apache.commons.net.MalformedServerReplyException;
  import  org.apache.commons.net.ftp.parser.MLSxEntryParser;
  import  org.apache.commons.net.io.CRLFLineReader;
  import  org.apache.commons.net.io.CopyStreamAdapter;
  import  org.apache.commons.net.io.CopyStreamEvent;
  import  org.apache.commons.net.io.CopyStreamListener;
  import  org.apache.commons.net.io.FromNetASCIIInputStream;
  import  org.apache.commons.net.io.ToNetASCIIOutputStream;
  import  org.apache.commons.net.io.Util;

FTPClient encapsulates all the functionality necessary to store and retrieve files from an FTP server. This class takes care of all low level details of interacting with an FTP server and provides a convenient higher level interface. As with all classes derived from org.apache.commons.net.SocketClient, you must first connect to the server with connect before doing anything, and finally disconnect after you're completely finished interacting with the server. Then you need to check the FTP reply code to see if the connection was successful. For example:
    FTPClient ftp = new FTPClient();
    FTPClientConfig config = new FTPClientConfig();
    config.setXXX(YYY); // change required options
    ftp.configure(config );
    boolean error = false;
    try {
      int reply;
      ftp.connect("ftp.foobar.com");
      System.out.println("Connected to " + server + ".");
      System.out.print(ftp.getReplyString());

      // After connection attempt, you should check the reply code to verify
      // success.
      reply = ftp.getReplyCode();

      if(!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        System.err.println("FTP server refused connection.");
        System.exit(1);
      }
      ... // transfer files
      ftp.logout();
    } catch(IOException e) {
      error = true;
      e.printStackTrace();
    } finally {
      if(ftp.isConnected()) {
        try {
          ftp.disconnect();
        } catch(IOException ioe) {
          // do nothing
        }
      }
      System.exit(error ? 1 : 0);
    }
 

Immediately after connecting is the only real time you need to check the reply code (because connect is of type void). The convention for all the FTP command methods in FTPClient is such that they either return a boolean value or some other value. The boolean methods return true on a successful completion reply from the FTP server and false on a reply resulting in an error condition or failure. The methods returning a value other than boolean return a value containing the higher level data produced by the FTP command, or null if a reply resulted in an error condition or failure. If you want to access the exact FTP reply code causing a success or failure, you must call getReplyCode after a success or failure.

The default settings for FTPClient are for it to use FTP.ASCII_FILE_TYPE , FTP.NON_PRINT_TEXT_FORMAT , FTP.STREAM_TRANSFER_MODE , and FTP.FILE_STRUCTURE . The only file types directly supported are FTP.ASCII_FILE_TYPE and FTP.BINARY_FILE_TYPE . Because there are at least 4 different EBCDIC encodings, we have opted not to provide direct support for EBCDIC. To transfer EBCDIC and other unsupported file types you must create your own filter InputStreams and OutputStreams and wrap them around the streams returned or required by the FTPClient methods. FTPClient uses the NetASCII filter streams to provide transparent handling of ASCII files. We will consider incorporating EBCDIC support if there is enough demand.

FTP.NON_PRINT_TEXT_FORMAT , FTP.STREAM_TRANSFER_MODE , and FTP.FILE_STRUCTURE are the only supported formats, transfer modes, and file structures.

Because the handling of sockets on different platforms can differ significantly, the FTPClient automatically issues a new PORT (or EPRT) command prior to every transfer requiring that the server connect to the client's data port. This ensures identical problem-free behavior on Windows, Unix, and Macintosh platforms. Additionally, it relieves programmers from having to issue the PORT (or EPRT) command themselves and dealing with platform dependent issues.

Additionally, for security purposes, all data connections to the client are verified to ensure that they originated from the intended party (host and port). If a data connection is initiated by an unexpected party, the command will close the socket and throw an IOException. You may disable this behavior with setRemoteVerificationEnabled().

You should keep in mind that the FTP server may choose to prematurely close a connection if the client has been idle for longer than a given time period (usually 900 seconds). The FTPClient class will detect a premature FTP server connection closing when it receives a FTPReply.SERVICE_NOT_AVAILABLE response to a command. When that occurs, the FTP class method encountering that reply will throw an org.apache.commons.net.ftp.FTPConnectionClosedException . FTPConnectionClosedException is a subclass of IOException and therefore need not be caught separately, but if you are going to catch it separately, its catch block must appear before the more general IOException catch block. When you encounter an org.apache.commons.net.ftp.FTPConnectionClosedException , you must disconnect the connection with disconnect() to properly clean up the system resources used by FTPClient. Before disconnecting, you may check the last reply code and text with getReplyCode , getReplyString , and getReplyStrings. You may avoid server disconnections while the client is idle by periodically sending NOOP commands to the server.

Rather than list it separately for each method, we mention here that every method communicating with the server and throwing an IOException can also throw a org.apache.commons.net.MalformedServerReplyException , which is a subclass of IOException. A MalformedServerReplyException will be thrown when the reply received from the server deviates enough from the protocol specification that it cannot be interpreted in a useful manner despite attempts to be as lenient as possible.

Listing API Examples Both paged and unpaged examples of directory listings are available, as follows:

Unpaged (whole list) access, using a parser accessible by auto-detect:

    FTPClient f = new FTPClient();
    f.connect(server);
    f.login(username, password);
    FTPFile[] files = f.listFiles(directory);
 

Paged access, using a parser not accessible by auto-detect. The class defined in the first parameter of initateListParsing should be derived from org.apache.commons.net.FTPFileEntryParser:

    FTPClient f = new FTPClient();
    f.connect(server);
    f.login(username, password);
    FTPListParseEngine engine =
       f.initiateListParsing("com.whatever.YourOwnParser", directory);

    while (engine.hasNext()) {
       FTPFile[] files = engine.getNext(25);  // "page size" you want
       //do whatever you want with these files, display them, etc.
       //expensive FTPFile objects not created until needed.
    }
 

Paged access, using a parser accessible by auto-detect:

    FTPClient f = new FTPClient();
    f.connect(server);
    f.login(username, password);
    FTPListParseEngine engine = f.initiateListParsing(directory);

    while (engine.hasNext()) {
       FTPFile[] files = engine.getNext(25);  // "page size" you want
       //do whatever you want with these files, display them, etc.
       //expensive FTPFile objects not created until needed.
    }
 

For examples of using FTPClient on servers whose directory listings

  • use languages other than English
  • use date formats other than the American English "standard" MM d yyyy
  • are in different timezones and you need accurate timestamps for dependency checking as in Ant
see FTPClientConfig FTPClientConfig.

Control channel keep-alive feature:
During file transfers, the data connection is busy, but the control connection is idle. FTP servers know that the control connection is in use, so won't close it through lack of activity, but it's a lot harder for network routers to know that the control and data connections are associated with each other. Some routers may treat the control connection as idle, and disconnect it if the transfer over the data connection takes longer than the allowable idle time for the router.
One solution to this is to send a safe command (i.e. NOOP) over the control connection to reset the router's idle timer. This is enabled as follows:

     ftpClient.setControlKeepAliveTimeout(300); // set timeout to 5 minutes
 
This will cause the file upload/download methods to send a NOOP approximately every 5 minutes.

The implementation currently uses a CopyStreamListener which is passed to the Util.copyStream(InputStream, OutputStream, int, long, CopyStreamListener, boolean) method, so the timing is partially dependent on how long each block transfer takes.

Note: this does not apply to the methods where the user is responsible for writing or reading the data stream, i.e. retrieveFileStream(String) , storeFileStream(String) and the other xxxFileStream methods

See also:
FTP_SYSTEM_TYPE
SYSTEM_TYPE_PROPERTIES
FTP
FTPConnectionClosedException
FTPFileEntryParser
FTPFileEntryParserFactory
DefaultFTPFileEntryParserFactory
FTPClientConfig
org.apache.commons.net.MalformedServerReplyException
 
 public class FTPClient extends FTP
 implements Configurable
 {
    
The system property () which can be used to override the system type.
If defined, the value will be used to create any automatically created parsers.

Since:
3.0
 
     public static final String FTP_SYSTEM_TYPE = "org.apache.commons.net.ftp.systemType";

    
The system property () which can be used as the default system type.
If defined, the value will be used if the SYST command fails.

Since:
3.1
 
     public static final String FTP_SYSTEM_TYPE_DEFAULT = "org.apache.commons.net.ftp.systemType.default";

    
The name of an optional systemType properties file (), which is loaded using Class.getResourceAsStream(String).
The entries are the systemType (as determined by FTPClient.getSystemType) and the values are the replacement type or parserClass, which is passed to FTPFileEntryParserFactory.createFileEntryParser(String).
For example:
 Plan 9=Unix
 OS410=org.apache.commons.net.ftp.parser.OS400FTPEntryParser
 

Since:
3.0
 
     public static final String SYSTEM_TYPE_PROPERTIES = "/systemType.properties";

    
A constant indicating the FTP session is expecting all transfers to occur between the client (local) and server and that the server should connect to the client's data port to initiate a data transfer. This is the default data connection mode when and FTPClient instance is created.
 
     public static final int ACTIVE_LOCAL_DATA_CONNECTION_MODE = 0;
    
A constant indicating the FTP session is expecting all transfers to occur between two remote servers and that the server the client is connected to should connect to the other server's data port to initiate a data transfer.
 
     public static final int ACTIVE_REMOTE_DATA_CONNECTION_MODE = 1;
    
A constant indicating the FTP session is expecting all transfers to occur between the client (local) and server and that the server is in passive mode, requiring the client to connect to the server's data port to initiate a transfer.
 
     public static final int PASSIVE_LOCAL_DATA_CONNECTION_MODE = 2;
    
A constant indicating the FTP session is expecting all transfers to occur between two remote servers and that the server the client is connected to is in passive mode, requiring the other server to connect to the first server's data port to initiate a data transfer.
 
     public static final int PASSIVE_REMOTE_DATA_CONNECTION_MODE = 3;
 
     private int __dataConnectionMode;
     private int __dataTimeout;
     private int __passivePort;
     private String __passiveHost;
     private final Random __random;
     private int __activeMinPort;
     private int __activeMaxPort;
     private InetAddress __reportActiveExternalHost// overrides __activeExternalHost in EPRT/PORT commands
     
The address to bind to on passive connections, if necessary.
 
     private InetAddress __passiveLocalHost;
 
     private int __fileType;
     @SuppressWarnings("unused"// fields are written, but currently not read
     private int __fileFormat;
     @SuppressWarnings("unused"// field is written, but currently not read
     private int __fileStructure;
     @SuppressWarnings("unused"// field is written, but currently not read
     private int __fileTransferMode;
     private boolean __remoteVerificationEnabled;
     private long __restartOffset;
     private int __bufferSize// buffersize for buffered data streams
     private int __sendDataSocketBufferSize;
     private int __receiveDataSocketBufferSize;
     private boolean __listHiddenFiles;
     private boolean __useEPSVwithIPv4// whether to attempt EPSV with an IPv4 connection
 
     // __systemName is a cached value that should not be referenced directly
     // except when assigned in getSystemName and __initDefaults.
     private String __systemName;
 
     // __entryParser is a cached value that should not be referenced directly
     // except when assigned in listFiles(String, String) and __initDefaults.
 
     // Key used to create the parser; necessary to ensure that the parser type is not ignored
     private String __entryParserKey;
 
     private FTPClientConfig __configuration;
 
     // Listener used by store/retrieve methods to handle keepalive
     private CopyStreamListener __copyStreamListener;
 
     // How long to wait before sending another control keep-alive message
     private long __controlKeepAliveTimeout;
 
     // How long to wait (ms) for keepalive message replies before continuing
     // Most FTP servers don't seem to support concurrent control and data connection usage
     private int __controlKeepAliveReplyTimeout=1000;

    
Enable or disable replacement of internal IP in passive mode. Default enabled.
 
     private boolean __passiveNatWorkaround = true;

    
Pattern for PASV mode responses. Groups: (n,n,n,n),(n),(n)
 
     private static final java.util.regex.Pattern __PARMS_PAT;
     static {
          = java.util.regex.Pattern.compile(
                 "(\\d{1,3},\\d{1,3},\\d{1,3},\\d{1,3}),(\\d{1,3}),(\\d{1,3})");
     }

    
Controls the automatic server encoding detection (only UTF-8 supported).
 
     private boolean __autodetectEncoding = false;

    
Map of FEAT responses. If null, has not been initialised.
 
     private HashMap<StringSet<String>> __featuresMap;
 
     private static class PropertiesSingleton {
 
         static final Properties PROPERTIES;
 
         static {
             InputStream resourceAsStream = FTPClient.class.getResourceAsStream();
             Properties p = null;
             if (resourceAsStream != null) {
                 p = new Properties();
                 try {
                     p.load(resourceAsStream);
                 } catch (IOException e) {
                 } finally {
                     try {
                         resourceAsStream.close();
                     } catch (IOException e) {
                         // Ignored
                     }
                 }
             }
              = p;
         }
 
     }
     private static Properties getOverrideProperties(){
         return .;
     }

    
Default FTPClient constructor. Creates a new FTPClient instance with the data connection mode set to ACTIVE_LOCAL_DATA_CONNECTION_MODE , the file type set to FTP.ASCII_FILE_TYPE , the file format set to FTP.NON_PRINT_TEXT_FORMAT , the file structure set to FTP.FILE_STRUCTURE , and the transfer mode set to FTP.STREAM_TRANSFER_MODE .

The list parsing auto-detect feature can be configured to use lenient future dates (short dates may be up to one day in the future) as follows:

 FTPClient ftp = new FTPClient();
 FTPClientConfig config = new FTPClientConfig();
 config.setLenientFutureDates(true);
 ftp.configure(config );
 
 
     public FTPClient()
     {
         __initDefaults();
          = -1;
          = true;
               = null;
          = false;
          = false;
          = new Random();
            = null;
     }
 
 
     private void __initDefaults()
     {
                 = null;
                 = -1;
          = null;
          = null;
          = 0;
          = 0;
                    = .;
               = .;
                  = .;
               = 0;
                  = null;
                 = null;
             = "";
          = null;
     }

    
Parse the pathname from a CWD reply.

According to RFC959 (http://www.ietf.org/rfc/rfc959.txt), it should be the same as for MKD i.e. 257<space>"<directory-name>"[<space>commentary] where any double-quotes in <directory-name> are doubled. Unlike MKD, the commentary is optional.

However, see NET-442 for an exception.

Parameters:
reply
Returns:
the pathname, without enclosing quotes, or the full string after the reply code and space if the syntax is invalid (i.e. enclosing quotes are missing or embedded quotes are not doubled)
 
     // package protected for access by test cases
     static String __parsePathname(String reply)
     {
         String param = reply.substring( + 1);
         if (param.startsWith("\"")) {
             StringBuilder sb = new StringBuilder();
             boolean quoteSeen = false;
             // start after initial quote
             for(int i=1; i < param.length(); i++) {
                 char ch = param.charAt(i);
                 if (ch=='"') {
                     if (quoteSeen) {
                         sb.append(ch);
                         quoteSeen=false;
                     } else {
                         // don't output yet, in case doubled
                         quoteSeen=true;
                     }
                 } else {
                     if (quoteSeen) { // found lone trailing quote within string
                         return sb.toString();
                     }
                     sb.append(ch); // just another character
                 }
             }
             if (quoteSeen) { // found lone trailing quote at end of string
                 return sb.toString();
             }
         }
         // malformed reply, return all after reply code and space
         return param;
     }

    

Since:
3.1
 
     protected void _parsePassiveModeReply(String reply)
     throws MalformedServerReplyException
     {
         java.util.regex.Matcher m = .matcher(reply);
         if (!m.find()) {
             throw new MalformedServerReplyException(
                     "Could not parse passive host information.\nServer Reply: " + reply);
         }
 
          = m.group(1).replace(',''.'); // Fix up to look like IP address
 
         try
         {
             int oct1 = Integer.parseInt(m.group(2));
             int oct2 = Integer.parseInt(m.group(3));
              = (oct1 << 8) | oct2;
         }
         catch (NumberFormatException e)
         {
             throw new MalformedServerReplyException(
                     "Could not parse passive port information.\nServer Reply: " + reply);
         }
 
         if () {
             try {
                 InetAddress host = InetAddress.getByName();
                 // reply is a local address, but target is not - assume NAT box changed the PASV reply
                 if (host.isSiteLocalAddress()) {
                     InetAddress remote = getRemoteAddress();
                     if (!remote.isSiteLocalAddress()){
                         String hostAddress = remote.getHostAddress();
                         fireReplyReceived(0,
                                     "[Replacing site local address "++" with "+hostAddress+"]\n");
                          = hostAddress;
                     }
                 }
             } catch (UnknownHostException e) { // Should not happen as we are passing in an IP address
                 throw new MalformedServerReplyException(
                         "Could not parse passive host information.\nServer Reply: " + reply);
             }
         }
     }
 
     protected void _parseExtendedPassiveModeReply(String reply)
     throws MalformedServerReplyException
     {
         reply = reply.substring(reply.indexOf('(') + 1,
                 reply.indexOf(')')).trim();
 
         char delim1delim2delim3delim4;
         delim1 = reply.charAt(0);
         delim2 = reply.charAt(1);
         delim3 = reply.charAt(2);
         delim4 = reply.charAt(reply.length()-1);
 
         if (!(delim1 == delim2) || !(delim2 == delim3)
                 || !(delim3 == delim4)) {
             throw new MalformedServerReplyException(
                     "Could not parse extended passive host information.\nServer Reply: " + reply);
         }
 
         int port;
         try
         {
             port = Integer.parseInt(reply.substring(3, reply.length()-1));
         }
         catch (NumberFormatException e)
         {
             throw new MalformedServerReplyException(
                     "Could not parse extended passive host information.\nServer Reply: " + reply);
         }
 
 
         // in EPSV mode, the passive host address is implicit
          = getRemoteAddress().getHostAddress();
          = port;
     }
 
     private boolean __storeFile(FTPCmd commandString remoteInputStream local)
     throws IOException
     {
         return _storeFile(command.getCommand(), remotelocal);
     }

    

Since:
3.1
 
     protected boolean _storeFile(String commandString remoteInputStream local)
     throws IOException
     {
         Socket socket = _openDataConnection_(commandremote);
 
         if (socket == null) {
             return false;
         }
 
         OutputStream output = getBufferedOutputStream(socket.getOutputStream());
 
         if ( == ) {
             output = new ToNetASCIIOutputStream(output);
         }
 
         CSL csl = null;
         if ( > 0) {
             csl = new CSL(this);
         }
 
         // Treat everything else as binary for now
         try
         {
             Util.copyStream(localoutputgetBufferSize(),
                     CopyStreamEvent.UNKNOWN_STREAM_SIZE, __mergeListeners(csl),
                     false);
         }
         catch (IOException e)
         {
             Util.closeQuietly(socket); // ignore close errors here
             if (csl != null) {
                 csl.cleanUp(); // fetch any outstanding keepalive replies
             }
             throw e;
         }
 
         output.close(); // ensure the file is fully written
         socket.close(); // done writing the file
         if (csl != null) {
             csl.cleanUp(); // fetch any outstanding keepalive replies
         }
         // Get the transfer response
         boolean ok = completePendingCommand();
         return ok;
     }
 
     private OutputStream __storeFileStream(FTPCmd commandString remote)
     throws IOException
     {
         return _storeFileStream(command.getCommand(), remote);
     }

    

Since:
3.1
 
     protected OutputStream _storeFileStream(String commandString remote)
     throws IOException
     {
         Socket socket = _openDataConnection_(commandremote);
 
         if (socket == null) {
             return null;
         }
 
         OutputStream output = socket.getOutputStream();
         if ( == ) {
             // We buffer ascii transfers because the buffering has to
             // be interposed between ToNetASCIIOutputSream and the underlying
             // socket output stream.  We don't buffer binary transfers
             // because we don't want to impose a buffering policy on the
             // programmer if possible.  Programmers can decide on their
             // own if they want to wrap the SocketOutputStream we return
             // for file types other than ASCII.
             output = getBufferedOutputStream(output);
             output = new ToNetASCIIOutputStream(output);
 
         }
         return new org.apache.commons.net.io.SocketOutputStream(socketoutput);
     }


    
Establishes a data connection with the FTP server, returning a Socket for the connection if successful. If a restart offset has been set with setRestartOffset(long), a REST command is issued to the server with the offset as an argument before establishing the data connection. Active mode connections also cause a local PORT command to be issued.

Deprecated:
(3.3) Use _openDataConnection_(FTPCmd, String) instead
Parameters:
command The int representation of the FTP command to send.
arg The arguments to the FTP command. If this parameter is set to null, then the command is sent with no argument.
Returns:
A Socket corresponding to the established data connection. Null is returned if an FTP protocol error is reported at any point during the establishment and initialization of the connection.
Throws:
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
 
     @Deprecated
     protected Socket _openDataConnection_(int commandString arg)
     throws IOException
     {
         return _openDataConnection_(FTPCommand.getCommand(command), arg);
     }

    
Establishes a data connection with the FTP server, returning a Socket for the connection if successful. If a restart offset has been set with setRestartOffset(long), a REST command is issued to the server with the offset as an argument before establishing the data connection. Active mode connections also cause a local PORT command to be issued.

Parameters:
command The int representation of the FTP command to send.
arg The arguments to the FTP command. If this parameter is set to null, then the command is sent with no argument.
Returns:
A Socket corresponding to the established data connection. Null is returned if an FTP protocol error is reported at any point during the establishment and initialization of the connection.
Throws:
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
Since:
3.3
 
     protected Socket _openDataConnection_(FTPCmd commandString arg)
     throws IOException
     {
         return _openDataConnection_(command.getCommand(), arg);
     }

    
Establishes a data connection with the FTP server, returning a Socket for the connection if successful. If a restart offset has been set with setRestartOffset(long), a REST command is issued to the server with the offset as an argument before establishing the data connection. Active mode connections also cause a local PORT command to be issued.

Parameters:
command The text representation of the FTP command to send.
arg The arguments to the FTP command. If this parameter is set to null, then the command is sent with no argument.
Returns:
A Socket corresponding to the established data connection. Null is returned if an FTP protocol error is reported at any point during the establishment and initialization of the connection.
Throws:
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
Since:
3.1
 
     protected Socket _openDataConnection_(String commandString arg)
     throws IOException
     {
                  != ) {
             return null;
         }
 
         final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address;
 
         Socket socket;
 
         {
             // if no activePortRange was set (correctly) -> getActivePort() = 0
             // -> new ServerSocket(0) -> bind to any free local port
             ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress());
 
             try {
                 // Try EPRT only if remote server is over IPv6, if not use PORT,
                 // because EPRT has no advantage over PORT on IPv4.
                 // It could even have the disadvantage,
                 // that EPRT will make the data connection fail, because
                 // today's intelligent NAT Firewalls are able to
                 // substitute IP addresses in the PORT command,
                 // but might not be able to recognize the EPRT command.
                 if (isInet6Address) {
                     if (!FTPReply.isPositiveCompletion(eprt(getReportHostAddress(), server.getLocalPort()))) {
                         return null;
                     }
                 } else {
                     if (!FTPReply.isPositiveCompletion(port(getReportHostAddress(), server.getLocalPort()))) {
                         return null;
                     }
                 }
 
                 if (( > 0) && !restart()) {
                     return null;
                 }
 
                 if (!FTPReply.isPositivePreliminary(sendCommand(commandarg))) {
                     return null;
                 }
 
                 // For now, let's just use the data timeout value for waiting for
                 // the data connection.  It may be desirable to let this be a
                 // separately configurable value.  In any case, we really want
                 // to allow preventing the accept from blocking indefinitely.
                 if ( >= 0) {
                     server.setSoTimeout();
                 }
                 socket = server.accept();
 
                 // Ensure the timeout is set before any commands are issued on the new socket
                 if ( >= 0) {
                     socket.setSoTimeout();
                 }
                 if ( > 0) {
                     socket.setReceiveBufferSize();
                 }
                 if ( > 0) {
                     socket.setSendBufferSize();
                 }
             } finally {
                 server.close();
             }
         }
         else
         { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE
 
             // Try EPSV command first on IPv6 - and IPv4 if enabled.
             // When using IPv4 with NAT it has the advantage
             // to work with more rare configurations.
             // E.g. if FTP server has a static PASV address (external network)
             // and the client is coming from another internal network.
             // In that case the data connection after PASV command would fail,
             // while EPSV would make the client succeed by taking just the port.
             boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address;
             if (attemptEPSV && epsv() == .)
             {
                 _parseExtendedPassiveModeReply(.get(0));
             }
             else
             {
                 if (isInet6Address) {
                     return null// Must use EPSV for IPV6
                 }
                 // If EPSV failed on IPV4, revert to PASV
                 if (pasv() != .) {
                     return null;
                 }
                 _parsePassiveModeReply(.get(0));
             }
 
             socket = _socketFactory_.createSocket();
             if ( > 0) {
                 socket.setReceiveBufferSize();
             }
             if ( > 0) {
                 socket.setSendBufferSize();
             }
             if ( != null) {
                 socket.bind(new InetSocketAddress(, 0));
             }
 
             // For now, let's just use the data timeout value for waiting for
             // the data connection.  It may be desirable to let this be a
             // separately configurable value.  In any case, we really want
             // to allow preventing the accept from blocking indefinitely.
             if ( >= 0) {
                 socket.setSoTimeout();
             }
 
             socket.connect(new InetSocketAddress(), connectTimeout);
             if (( > 0) && !restart())
             {
                 socket.close();
                 return null;
             }
 
             if (!FTPReply.isPositivePreliminary(sendCommand(commandarg)))
             {
                 socket.close();
                 return null;
             }
         }
 
         if ( && !verifyRemote(socket))
         {
             socket.close();
 
             throw new IOException(
                     "Host attempting data connection " + socket.getInetAddress().getHostAddress() +
                     " is not same as server " + getRemoteAddress().getHostAddress());
         }
 
         return socket;
     }
 
 
     @Override
     protected void _connectAction_() throws IOException
     {
         super._connectAction_(); // sets up _input_ and _output_
         __initDefaults();
         // must be after super._connectAction_(), because otherwise we get an
         // Exception claiming we're not connected
         if (  )
         {
             ArrayList<StringoldReplyLines = new ArrayList<String> ();
             int oldReplyCode = ;
             if ( hasFeature("UTF8") || hasFeature("UTF-8")) // UTF8 appears to be the default
             {
                  setControlEncoding("UTF-8");
                   =
                      new CRLFLineReader(new InputStreamReader(_input_, getControlEncoding()));
                   =
                     new BufferedWriter(new OutputStreamWriter(_output_, getControlEncoding()));
             }
             // restore the original reply (server greeting)
             .clear();
             .addAll(oldReplyLines);
              = oldReplyCode;
         }
     }


    
Sets the timeout in milliseconds to use when reading from the data connection. This timeout will be set immediately after opening the data connection, provided that the value is &ge; 0.

Note: the timeout will also be applied when calling accept() whilst establishing an active local data connection.

Parameters:
timeout The default timeout in milliseconds that is used when opening a data connection socket. The value 0 means an infinite timeout.
 
     public void setDataTimeout(int timeout)
     {
          = timeout;
     }

    
set the factory used for parser creation to the supplied factory object.

Parameters:
parserFactory factory object used to create FTPFileEntryParsers
See also:
org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory
org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory
 
     public void setParserFactory(FTPFileEntryParserFactory parserFactory) {
          = parserFactory;
     }


    
Closes the connection to the FTP server and restores connection parameters to the default values.

Throws:
IOException If an error occurs while disconnecting.
 
     @Override
     public void disconnect() throws IOException
     {
         super.disconnect();
         __initDefaults();
     }


    
Enable or disable verification that the remote host taking part of a data connection is the same as the host to which the control connection is attached. The default is for verification to be enabled. You may set this value at any time, whether the FTPClient is currently connected or not.

Parameters:
enable True to enable verification, false to disable verification.
 
    public void setRemoteVerificationEnabled(boolean enable)
    {
         = enable;
    }

    
Return whether or not verification of the remote host participating in data connections is enabled. The default behavior is for verification to be enabled.

Returns:
True if verification is enabled, false if not.
    public boolean isRemoteVerificationEnabled()
    {
        return ;
    }

    
Login to the FTP server using the provided username and password.

Parameters:
username The username to login under.
password The password to use.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean login(String usernameString passwordthrows IOException
    {
        user(username);
        if (FTPReply.isPositiveCompletion()) {
            return true;
        }
        // If we get here, we either have an error code, or an intermmediate
        // reply requesting password.
        if (!FTPReply.isPositiveIntermediate()) {
            return false;
        }
        return FTPReply.isPositiveCompletion(pass(password));
    }


    
Login to the FTP server using the provided username, password, and account. If no account is required by the server, only the username and password, the account information is not used.

Parameters:
username The username to login under.
password The password to use.
account The account to use.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean login(String usernameString passwordString account)
    throws IOException
    {
        user(username);
        if (FTPReply.isPositiveCompletion()) {
            return true;
        }
        // If we get here, we either have an error code, or an intermmediate
        // reply requesting password.
        if (!FTPReply.isPositiveIntermediate()) {
            return false;
        }
        pass(password);
        if (FTPReply.isPositiveCompletion()) {
            return true;
        }
        if (!FTPReply.isPositiveIntermediate()) {
            return false;
        }
        return FTPReply.isPositiveCompletion(acct(account));
    }

    
Logout of the FTP server by sending the QUIT command.

Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean logout() throws IOException
    {
        return FTPReply.isPositiveCompletion(quit());
    }


    
Change the current working directory of the FTP session.

Parameters:
pathname The new current working directory.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean changeWorkingDirectory(String pathnamethrows IOException
    {
        return FTPReply.isPositiveCompletion(cwd(pathname));
    }


    
Change to the parent directory of the current working directory.

Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean changeToParentDirectory() throws IOException
    {
        return FTPReply.isPositiveCompletion(cdup());
    }


    
Issue the FTP SMNT command.

Parameters:
pathname The pathname to mount.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean structureMount(String pathnamethrows IOException
    {
        return FTPReply.isPositiveCompletion(smnt(pathname));
    }

    
Reinitialize the FTP session. Not all FTP servers support this command, which issues the FTP REIN command.

Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    boolean reinitialize() throws IOException
    {
        rein();
        if (FTPReply.isPositiveCompletion() ||
                (FTPReply.isPositivePreliminary() &&
                        FTPReply.isPositiveCompletion(getReply())))
        {
            __initDefaults();
            return true;
        }
        return false;
    }


    
Set the current data connection mode to ACTIVE_LOCAL_DATA_CONNECTION_MODE. No communication with the FTP server is conducted, but this causes all future data transfers to require the FTP server to connect to the client's data port. Additionally, to accommodate differences between socket implementations on different platforms, this method causes the client to issue a PORT command before every data transfer.
    public void enterLocalActiveMode()
    {
         = null;
         = -1;
    }


    
Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE . Use this method only for data transfers between the client and server. This method causes a PASV (or EPSV) command to be issued to the server before the opening of every data connection, telling the server to open a data port to which the client will connect to conduct data transfers. The FTPClient will stay in PASSIVE_LOCAL_DATA_CONNECTION_MODE until the mode is changed by calling some other method such as enterLocalActiveMode()

N.B. currently calling any connect method will reset the mode to ACTIVE_LOCAL_DATA_CONNECTION_MODE.

    public void enterLocalPassiveMode()
    {
        // These will be set when just before a data connection is opened
        // in _openDataConnection_()
         = null;
         = -1;
    }


    
Set the current data connection mode to ACTIVE_REMOTE_DATA_CONNECTION . Use this method only for server to server data transfers. This method issues a PORT command to the server, indicating the other server and port to which it should connect for data transfers. You must call this method before EVERY server to server transfer attempt. The FTPClient will NOT automatically continue to issue PORT commands. You also must remember to call enterLocalActiveMode() if you wish to return to the normal data connection mode.

Parameters:
host The passive mode server accepting connections for data transfers.
port The passive mode server's data port.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean enterRemoteActiveMode(InetAddress hostint port)
    throws IOException
    {
        if (FTPReply.isPositiveCompletion(port(hostport)))
        {
             = null;
             = -1;
            return true;
        }
        return false;
    }

    
Set the current data connection mode to PASSIVE_REMOTE_DATA_CONNECTION_MODE . Use this method only for server to server data transfers. This method issues a PASV command to the server, telling it to open a data port to which the active server will connect to conduct data transfers. You must call this method before EVERY server to server transfer attempt. The FTPClient will NOT automatically continue to issue PASV commands. You also must remember to call enterLocalActiveMode() if you wish to return to the normal data connection mode.

Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean enterRemotePassiveMode() throws IOException
    {
        if (pasv() != .) {
            return false;
        }
        return true;
    }

    
Returns the hostname or IP address (in the form of a string) returned by the server when entering passive mode. If not in passive mode, returns null. This method only returns a valid value AFTER a data connection has been opened after a call to enterLocalPassiveMode(). This is because FTPClient sends a PASV command to the server only just before opening a data connection, and not when you call enterLocalPassiveMode().

Returns:
The passive host name if in passive mode, otherwise null.
    public String getPassiveHost()
    {
        return ;
    }

    
If in passive mode, returns the data port of the passive host. This method only returns a valid value AFTER a data connection has been opened after a call to enterLocalPassiveMode(). This is because FTPClient sends a PASV command to the server only just before opening a data connection, and not when you call enterLocalPassiveMode().

Returns:
The data port of the passive server. If not in passive mode, undefined.
    public int getPassivePort()
    {
        return ;
    }


    
Returns the current data connection mode (one of the _DATA_CONNECTION_MODE constants.

Returns:
The current data connection mode (one of the _DATA_CONNECTION_MODE constants.
    public int getDataConnectionMode()
    {
        return ;
    }

    
Get the client port for active mode.

Returns:
The client port for active mode.
    private int getActivePort()
    {
        if ( > 0 &&  >= )
        {
            if ( == ) {
                return ;
            }
            // Get a random port between the min and max port range
            return .nextInt( -  + 1) + ;
        }
        else
        {
            // default port
            return 0;
        }
    }

    
Get the host address for active mode; allows the local address to be overridden.

Returns:
__activeExternalHost if non-null, else getLocalAddress()
See also:
setActiveExternalIPAddress(String)
    private InetAddress getHostAddress()
    {
        if ( != null)
        {
            return ;
        }
        else
        {
            // default local address
            return getLocalAddress();
        }
    }

    
Get the reported host address for active mode EPRT/PORT commands; allows override of getHostAddress(). Useful for FTP Client behind Firewall NAT.

Returns:
__reportActiveExternalHost if non-null, else getHostAddress();
    private InetAddress getReportHostAddress() {
        if ( != null) {
            return  ;
        } else {
            return getHostAddress();
        }
    }

    
Set the client side port range in active mode.

Parameters:
minPort The lowest available port (inclusive).
maxPort The highest available port (inclusive).
Since:
2.2
    public void setActivePortRange(int minPortint maxPort)
    {
        this. = minPort;
        this. = maxPort;
    }

    
Set the external IP address in active mode. Useful when there are multiple network cards.

Parameters:
ipAddress The external IP address of this machine.
Throws:
UnknownHostException if the ipAddress cannot be resolved
Since:
2.2
    public void setActiveExternalIPAddress(String ipAddressthrows UnknownHostException
    {
        this. = InetAddress.getByName(ipAddress);
    }

    
Set the local IP address to use in passive mode. Useful when there are multiple network cards.

Parameters:
ipAddress The local IP address of this machine.
Throws:
UnknownHostException if the ipAddress cannot be resolved
    public void setPassiveLocalIPAddress(String ipAddressthrows UnknownHostException
    {
        this. = InetAddress.getByName(ipAddress);
    }

    
Set the local IP address to use in passive mode. Useful when there are multiple network cards.

Parameters:
inetAddress The local IP address of this machine.
    public void setPassiveLocalIPAddress(InetAddress inetAddress)
    {
        this. = inetAddress;
    }

    
Set the local IP address in passive mode. Useful when there are multiple network cards.

Returns:
The local IP address in passive mode.
    {
        return this.;
    }

    
Set the external IP address to report in EPRT/PORT commands in active mode. Useful when there are multiple network cards.

Parameters:
ipAddress The external IP address of this machine.
Throws:
UnknownHostException if the ipAddress cannot be resolved
Since:
3.1
See also:
getReportHostAddress()
    public void setReportActiveExternalIPAddress(String ipAddressthrows UnknownHostException
    {
        this. = InetAddress.getByName(ipAddress);
    }


    
Sets the file type to be transferred. This should be one of FTP.ASCII_FILE_TYPE , FTP.BINARY_FILE_TYPE, etc. The file type only needs to be set when you want to change the type. After changing it, the new type stays in effect until you change it again. The default file type is FTP.ASCII_FILE_TYPE if this method is never called.
The server default is supposed to be ASCII (see RFC 959), however many ftp servers default to BINARY. To ensure correct operation with all servers, always specify the appropriate file type after connecting to the server.

N.B. currently calling any connect method will reset the type to FTP.ASCII_FILE_TYPE.

Parameters:
fileType The _FILE_TYPE constant indcating the type of file.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean setFileType(int fileTypethrows IOException
    {
        if (FTPReply.isPositiveCompletion(type(fileType)))
        {
             = fileType;
             = .;
            return true;
        }
        return false;
    }


    
Sets the file type to be transferred and the format. The type should be one of FTP.ASCII_FILE_TYPE , FTP.BINARY_FILE_TYPE , etc. The file type only needs to be set when you want to change the type. After changing it, the new type stays in effect until you change it again. The default file type is FTP.ASCII_FILE_TYPE if this method is never called.
The server default is supposed to be ASCII (see RFC 959), however many ftp servers default to BINARY. To ensure correct operation with all servers, always specify the appropriate file type after connecting to the server.
The format should be one of the FTP class TEXT_FORMAT constants, or if the type is FTP.LOCAL_FILE_TYPE , the format should be the byte size for that type. The default format is FTP.NON_PRINT_TEXT_FORMAT if this method is never called.

N.B. currently calling any connect method will reset the type to FTP.ASCII_FILE_TYPE and the formatOrByteSize to FTP.NON_PRINT_TEXT_FORMAT.

Parameters:
fileType The _FILE_TYPE constant indcating the type of file.
formatOrByteSize The format of the file (one of the _FORMAT constants. In the case of LOCAL_FILE_TYPE, the byte size.

Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean setFileType(int fileTypeint formatOrByteSize)
    throws IOException
    {
        if (FTPReply.isPositiveCompletion(type(fileTypeformatOrByteSize)))
        {
             = fileType;
             = formatOrByteSize;
            return true;
        }
        return false;
    }


    
Sets the file structure. The default structure is FTP.FILE_STRUCTURE if this method is never called or if a connect method is called.

Parameters:
structure The structure of the file (one of the FTP class _STRUCTURE constants).
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean setFileStructure(int structurethrows IOException
    {
        if (FTPReply.isPositiveCompletion(stru(structure)))
        {
             = structure;
            return true;
        }
        return false;
    }


    
Sets the transfer mode. The default transfer mode FTP.STREAM_TRANSFER_MODE if this method is never called or if a connect method is called.

Parameters:
mode The new transfer mode to use (one of the FTP class _TRANSFER_MODE constants).
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean setFileTransferMode(int modethrows IOException
    {
        if (FTPReply.isPositiveCompletion(mode(mode)))
        {
             = mode;
            return true;
        }
        return false;
    }


    
Initiate a server to server file transfer. This method tells the server to which the client is connected to retrieve a given file from the other server.

Parameters:
filename The name of the file to retrieve.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean remoteRetrieve(String filenamethrows IOException
    {
                 == ) {
            return FTPReply.isPositivePreliminary(retr(filename));
        }
        return false;
    }


    
Initiate a server to server file transfer. This method tells the server to which the client is connected to store a file on the other server using the given filename. The other server must have had a remoteRetrieve issued to it by another FTPClient.

Parameters:
filename The name to call the file that is to be stored.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean remoteStore(String filenamethrows IOException
    {
                 == ) {
            return FTPReply.isPositivePreliminary(stor(filename));
        }
        return false;
    }


    
Initiate a server to server file transfer. This method tells the server to which the client is connected to store a file on the other server using a unique filename based on the given filename. The other server must have had a remoteRetrieve issued to it by another FTPClient.

Parameters:
filename The name on which to base the filename of the file that is to be stored.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean remoteStoreUnique(String filenamethrows IOException
    {
                 == ) {
            return FTPReply.isPositivePreliminary(stou(filename));
        }
        return false;
    }


    
Initiate a server to server file transfer. This method tells the server to which the client is connected to store a file on the other server using a unique filename. The other server must have had a remoteRetrieve issued to it by another FTPClient. Many FTP servers require that a base filename be given from which the unique filename can be derived. For those servers use the other version of remoteStoreUnique

Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean remoteStoreUnique() throws IOException
    {
                 == ) {
            return FTPReply.isPositivePreliminary(stou());
        }
        return false;
    }
    // For server to server transfers
    
Initiate a server to server file transfer. This method tells the server to which the client is connected to append to a given file on the other server. The other server must have had a remoteRetrieve issued to it by another FTPClient.

Parameters:
filename The name of the file to be appended to, or if the file does not exist, the name to call the file being stored.

Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean remoteAppend(String filenamethrows IOException
    {
                 == ) {
            return FTPReply.isPositivePreliminary(appe(filename));
        }
        return false;
    }

    
There are a few FTPClient methods that do not complete the entire sequence of FTP commands to complete a transaction. These commands require some action by the programmer after the reception of a positive intermediate command. After the programmer's code completes its actions, it must call this method to receive the completion reply from the server and verify the success of the entire transaction.

For example,

 InputStream input;
 OutputStream output;
 input  = new FileInputStream("foobaz.txt");
 output = ftp.storeFileStream("foobar.txt")
 if(!FTPReply.isPositiveIntermediate(ftp.getReplyCode())) {
     input.close();
     output.close();
     ftp.logout();
     ftp.disconnect();
     System.err.println("File transfer failed.");
     System.exit(1);
 }
 Util.copyStream(input, output);
 input.close();
 output.close();
 // Must call completePendingCommand() to finish command.
 if(!ftp.completePendingCommand()) {
     ftp.logout();
     ftp.disconnect();
     System.err.println("File transfer failed.");
     System.exit(1);
 }
 

Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean completePendingCommand() throws IOException
    {
        return FTPReply.isPositiveCompletion(getReply());
    }


    
Retrieves a named file from the server and writes it to the given OutputStream. This method does NOT close the given OutputStream. If the current file type is ASCII, line separators in the file are converted to the local representation.

Note: if you have used setRestartOffset(long), the file data will start from the selected offset.

Parameters:
remote The name of the remote file.
local The local OutputStream to which to write the file.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
org.apache.commons.net.io.CopyStreamException If an I/O error occurs while actually transferring the file. The CopyStreamException allows you to determine the number of bytes transferred and the IOException causing the error. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean retrieveFile(String remoteOutputStream local)
    throws IOException
    {
        return _retrieveFile(..getCommand(), remotelocal);
    }

    

Since:
3.1
    protected boolean _retrieveFile(String commandString remoteOutputStream local)
    throws IOException
    {
        Socket socket = _openDataConnection_(commandremote);
        if (socket == null) {
            return false;
        }
        InputStream input = getBufferedInputStream(socket.getInputStream());
        if ( == ) {
            input = new FromNetASCIIInputStream(input);
        }
        CSL csl = null;
        if ( > 0) {
            csl = new CSL(this);
        }
        // Treat everything else as binary for now
        try
        {
            Util.copyStream(inputlocalgetBufferSize(),
                    CopyStreamEvent.UNKNOWN_STREAM_SIZE, __mergeListeners(csl),
                    false);
        } finally {
            Util.closeQuietly(input);
            Util.closeQuietly(socket);
            if (csl != null) {
                csl.cleanUp(); // fetch any outstanding keepalive replies
            }
        }
        // Get the transfer response
        boolean ok = completePendingCommand();
        return ok;
    }

    
Returns an InputStream from which a named file from the server can be read. If the current file type is ASCII, the returned InputStream will convert line separators in the file to the local representation. You must close the InputStream when you finish reading from it. The InputStream itself will take care of closing the parent data connection socket upon being closed. To finalize the file transfer you must call completePendingCommand and check its return value to verify success.

Note: if you have used setRestartOffset(long), the file data will start from the selected offset.

Parameters:
remote The name of the remote file.
Returns:
An InputStream from which the remote file can be read. If the data connection cannot be opened (e.g., the file does not exist), null is returned (in which case you may check the reply code to determine the exact reason for failure).
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public InputStream retrieveFileStream(String remotethrows IOException
    {
        return _retrieveFileStream(..getCommand(), remote);
    }

    

Since:
3.1
    protected InputStream _retrieveFileStream(String commandString remote)
    throws IOException
    {
        Socket socket = _openDataConnection_(commandremote);
        if (socket == null) {
            return null;
        }
        InputStream input = socket.getInputStream();
        if ( == ) {
            // We buffer ascii transfers because the buffering has to
            // be interposed between FromNetASCIIOutputSream and the underlying
            // socket input stream.  We don't buffer binary transfers
            // because we don't want to impose a buffering policy on the
            // programmer if possible.  Programmers can decide on their
            // own if they want to wrap the SocketInputStream we return
            // for file types other than ASCII.
            input = getBufferedInputStream(input);
            input = new FromNetASCIIInputStream(input);
        }
        return new org.apache.commons.net.io.SocketInputStream(socketinput);
    }


    
Stores a file on the server using the given name and taking input from the given InputStream. This method does NOT close the given InputStream. If the current file type is ASCII, line separators in the file are transparently converted to the NETASCII format (i.e., you should not attempt to create a special InputStream to do this).

Parameters:
remote The name to give the remote file.
local The local InputStream from which to read the file.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
org.apache.commons.net.io.CopyStreamException If an I/O error occurs while actually transferring the file. The CopyStreamException allows you to determine the number of bytes transferred and the IOException causing the error. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean storeFile(String remoteInputStream local)
    throws IOException
    {
        return __storeFile(.remotelocal);
    }


    
Returns an OutputStream through which data can be written to store a file on the server using the given name. If the current file type is ASCII, the returned OutputStream will convert line separators in the file to the NETASCII format (i.e., you should not attempt to create a special OutputStream to do this). You must close the OutputStream when you finish writing to it. The OutputStream itself will take care of closing the parent data connection socket upon being closed. To finalize the file transfer you must call completePendingCommand and check its return value to verify success.

Parameters:
remote The name to give the remote file.
Returns:
An OutputStream through which the remote file can be written. If the data connection cannot be opened (e.g., the file does not exist), null is returned (in which case you may check the reply code to determine the exact reason for failure).
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public OutputStream storeFileStream(String remotethrows IOException
    {
        return __storeFileStream(.remote);
    }

    
Appends to a file on the server with the given name, taking input from the given InputStream. This method does NOT close the given InputStream. If the current file type is ASCII, line separators in the file are transparently converted to the NETASCII format (i.e., you should not attempt to create a special InputStream to do this).

Parameters:
remote The name of the remote file.
local The local InputStream from which to read the data to be appended to the remote file.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
org.apache.commons.net.io.CopyStreamException If an I/O error occurs while actually transferring the file. The CopyStreamException allows you to determine the number of bytes transferred and the IOException causing the error. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean appendFile(String remoteInputStream local)
    throws IOException
    {
        return __storeFile(.remotelocal);
    }

    
Returns an OutputStream through which data can be written to append to a file on the server with the given name. If the current file type is ASCII, the returned OutputStream will convert line separators in the file to the NETASCII format (i.e., you should not attempt to create a special OutputStream to do this). You must close the OutputStream when you finish writing to it. The OutputStream itself will take care of closing the parent data connection socket upon being closed. To finalize the file transfer you must call completePendingCommand and check its return value to verify success.

Parameters:
remote The name of the remote file.
Returns:
An OutputStream through which the remote file can be appended. If the data connection cannot be opened (e.g., the file does not exist), null is returned (in which case you may check the reply code to determine the exact reason for failure).
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public OutputStream appendFileStream(String remotethrows IOException
    {
        return __storeFileStream(.remote);
    }

    
Stores a file on the server using a unique name derived from the given name and taking input from the given InputStream. This method does NOT close the given InputStream. If the current file type is ASCII, line separators in the file are transparently converted to the NETASCII format (i.e., you should not attempt to create a special InputStream to do this).

Parameters:
remote The name on which to base the unique name given to the remote file.
local The local InputStream from which to read the file.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
org.apache.commons.net.io.CopyStreamException If an I/O error occurs while actually transferring the file. The CopyStreamException allows you to determine the number of bytes transferred and the IOException causing the error. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean storeUniqueFile(String remoteInputStream local)
    throws IOException
    {
        return __storeFile(.remotelocal);
    }


    
Returns an OutputStream through which data can be written to store a file on the server using a unique name derived from the given name. If the current file type is ASCII, the returned OutputStream will convert line separators in the file to the NETASCII format (i.e., you should not attempt to create a special OutputStream to do this). You must close the OutputStream when you finish writing to it. The OutputStream itself will take care of closing the parent data connection socket upon being closed. To finalize the file transfer you must call completePendingCommand and check its return value to verify success.

Parameters:
remote The name on which to base the unique name given to the remote file.
Returns:
An OutputStream through which the remote file can be written. If the data connection cannot be opened (e.g., the file does not exist), null is returned (in which case you may check the reply code to determine the exact reason for failure).
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public OutputStream storeUniqueFileStream(String remotethrows IOException
    {
        return __storeFileStream(.remote);
    }

    
Stores a file on the server using a unique name assigned by the server and taking input from the given InputStream. This method does NOT close the given InputStream. If the current file type is ASCII, line separators in the file are transparently converted to the NETASCII format (i.e., you should not attempt to create a special InputStream to do this).

Parameters:
local The local InputStream from which to read the file.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
org.apache.commons.net.io.CopyStreamException If an I/O error occurs while actually transferring the file. The CopyStreamException allows you to determine the number of bytes transferred and the IOException causing the error. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean storeUniqueFile(InputStream localthrows IOException
    {
        return __storeFile(.nulllocal);
    }

    
Returns an OutputStream through which data can be written to store a file on the server using a unique name assigned by the server. If the current file type is ASCII, the returned OutputStream will convert line separators in the file to the NETASCII format (i.e., you should not attempt to create a special OutputStream to do this). You must close the OutputStream when you finish writing to it. The OutputStream itself will take care of closing the parent data connection socket upon being closed. To finalize the file transfer you must call completePendingCommand and check its return value to verify success.

Returns:
An OutputStream through which the remote file can be written. If the data connection cannot be opened (e.g., the file does not exist), null is returned (in which case you may check the reply code to determine the exact reason for failure).
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    {
        return __storeFileStream(.null);
    }

    
Reserve a number of bytes on the server for the next file transfer.

Parameters:
bytes The number of bytes which the server should allocate.
Returns:
True if successfully completed, false if not.
Throws:
FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean allocate(int bytesthrows IOException
    {
        return FTPReply.isPositiveCompletion(allo(bytes));
    }

    
Query the server for supported features. The server may reply with a list of server-supported exensions. For example, a typical client-server interaction might be (from RFC 2389):
C> feat
S> 211-Extensions supported:
S>  MLST size*;create;modify*;perm;media-type
S>  SIZE
S>  COMPRESSION
S>  MDTM
S> 211 END
 

Returns:
True if successfully completed, false if not.
Throws:
IOException
Since:
2.2
See also:
http://www.faqs.org/rfcs/rfc2389.html
    public boolean features() throws IOException {
        return FTPReply.isPositiveCompletion(feat());
    }

    
Query the server for a supported feature, and returns its values (if any). Caches the parsed response to avoid resending the command repeatedly.

Returns:
if the feature is present, returns the feature values (empty array if none) Returns null if the feature is not found or the command failed. Check getReplyCode() or getReplyString() if so.
Throws:
IOException
Since:
3.0
    public String[] featureValues(String featurethrows IOException {
        if (!initFeatureMap()) {
            return null;
        }