ftpclient.java

来自「apache推出的net包」· Java 代码 · 共 1,527 行 · 第 1/5 页

JAVA
1,527
字号
    private void __initDefaults()    {        __dataConnectionMode = ACTIVE_LOCAL_DATA_CONNECTION_MODE;        __passiveHost        = null;        __passivePort        = -1;        __fileType           = FTP.ASCII_FILE_TYPE;        __fileStructure      = FTP.FILE_STRUCTURE;        __fileFormat         = FTP.NON_PRINT_TEXT_FORMAT;        __fileTransferMode   = FTP.STREAM_TRANSFER_MODE;        __restartOffset      = 0;        __systemName         = null;        __entryParser        = null;        __bufferSize 		 = Util.DEFAULT_COPY_BUFFER_SIZE;    }        private String __parsePathname(String reply)    {        int begin, end;        begin = reply.indexOf('"') + 1;        end = reply.indexOf('"', begin);        return reply.substring(begin, end);    }    private void __parsePassiveModeReply(String reply)    throws MalformedServerReplyException    {        int i, index, lastIndex;        String octet1, octet2;        StringBuffer host;        reply = reply.substring(reply.indexOf('(') + 1,                                reply.indexOf(')')).trim();        host = new StringBuffer(24);        lastIndex = 0;        index = reply.indexOf(',');        host.append(reply.substring(lastIndex, index));        for (i = 0; i < 3; i++)        {            host.append('.');            lastIndex = index + 1;            index = reply.indexOf(',', lastIndex);            host.append(reply.substring(lastIndex, index));        }        lastIndex = index + 1;        index = reply.indexOf(',', lastIndex);        octet1 = reply.substring(lastIndex, index);        octet2 = reply.substring(index + 1);        // index and lastIndex now used as temporaries        try        {            index = Integer.parseInt(octet1);            lastIndex = Integer.parseInt(octet2);        }        catch (NumberFormatException e)        {            throw new MalformedServerReplyException(                "Could not parse passive host information.\nServer Reply: " + reply);        }        index <<= 8;        index |= lastIndex;        __passiveHost = host.toString();        __passivePort = index;    }    private boolean __storeFile(int command, String remote, InputStream local)    throws IOException    {        OutputStream output;        Socket socket;        if ((socket = _openDataConnection_(command, remote)) == null)            return false;        output = new BufferedOutputStream(socket.getOutputStream(),                                          getBufferSize()                                          );        if (__fileType == ASCII_FILE_TYPE)            output = new ToNetASCIIOutputStream(output);        // Treat everything else as binary for now        try        {            Util.copyStream(local, output, getBufferSize(),                            CopyStreamEvent.UNKNOWN_STREAM_SIZE, null,                            false);        }        catch (IOException e)        {            try            {                socket.close();            }            catch (IOException f)            {}            throw e;        }        output.close();        socket.close();        return completePendingCommand();    }    private OutputStream __storeFileStream(int command, String remote)    throws IOException    {        OutputStream output;        Socket socket;        if ((socket = _openDataConnection_(command, remote)) == null)            return null;        output = socket.getOutputStream();        if (__fileType == ASCII_FILE_TYPE) {          // 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 = new BufferedOutputStream(output,                                            getBufferSize());          output = new ToNetASCIIOutputStream(output);        }        return new org.apache.commons.net.io.SocketOutputStream(socket, output);    }    /**     * Establishes a data connection with the FTP server, returning     * a Socket for the connection if successful.  If a restart     * offset has been set with {@link #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.     * <p>     * @param command  The text representation of the FTP command to send.     * @param arg The arguments to the FTP command.  If this parameter is     *             set to null, then the command is sent with no argument.     * @return 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.     * @exception IOException  If an I/O error occurs while either sending a     *      command to the server or receiving a reply from the server.     */    protected Socket _openDataConnection_(int command, String arg)      throws IOException    {        Socket socket;        if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE &&                __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE)            return null;        if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE)        {            ServerSocket server;            server = _socketFactory_.createServerSocket(0, 1, getLocalAddress());            if (!FTPReply.isPositiveCompletion(port(getLocalAddress(),                                                    server.getLocalPort())))            {                server.close();                return null;            }            if ((__restartOffset > 0) && !restart(__restartOffset))            {                server.close();                return null;            }            if (!FTPReply.isPositivePreliminary(sendCommand(command, arg)))            {                server.close();                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 (__dataTimeout >= 0)                server.setSoTimeout(__dataTimeout);            socket = server.accept();            server.close();        }        else        { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE            if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)                return null;            __parsePassiveModeReply((String)_replyLines.elementAt(0));            socket = _socketFactory_.createSocket(__passiveHost, __passivePort);            if ((__restartOffset > 0) && !restart(__restartOffset))            {                socket.close();                return null;            }            if (!FTPReply.isPositivePreliminary(sendCommand(command, arg)))            {                socket.close();                return null;            }        }        if (__remoteVerificationEnabled && !verifyRemote(socket))        {            InetAddress host1, host2;            host1 = socket.getInetAddress();            host2 = getRemoteAddress();            socket.close();            throw new IOException(                "Host attempting data connection " + host1.getHostAddress() +                " is not same as server " + host2.getHostAddress());        }        if (__dataTimeout >= 0)            socket.setSoTimeout(__dataTimeout);        return socket;    }    protected void _connectAction_() throws IOException    {        super._connectAction_();        __initDefaults();    }    /***     * Sets the timeout in milliseconds to use when reading from the     * data connection.  This timeout will be set immediately after     * opening the data connection.     * <p>     * @param  timeout The default timeout in milliseconds that is used when     *        opening a data connection socket.     ***/    public void setDataTimeout(int timeout)    {        __dataTimeout = timeout;    }    /**     * set the factory used for parser creation to the supplied factory object.     *     * @param parserFactory     *               factory object used to create FTPFileEntryParsers     *     * @see org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory     * @see org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory     */    public void setParserFactory(FTPFileEntryParserFactory parserFactory) {        __parserFactory = parserFactory;    }    /***     * Closes the connection to the FTP server and restores     * connection parameters to the default values.     * <p>     * @exception IOException If an error occurs while disconnecting.     ***/    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.     * <p>     * @param enable True to enable verification, false to disable verification.     ***/    public void setRemoteVerificationEnabled(boolean enable)    {        __remoteVerificationEnabled = 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.

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?