⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ftpclient.java

📁 java ftp 鞭策帮手 可一啊啊觉得上
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
     *
     *  @param   password       The password.
     */
    public void password(String password)
        throws IOException, FTPException {
    	
    	checkConnection(true);
    	
        lastReply = control.sendCommand("PASS " + password);

        // we allow for a site with no passwords (202) or requiring
        // ACCT info (332)
        String[] validCodes = {"230", "202", "332"};
        lastValidReply = control.validateReply(lastReply, validCodes);
    }
    
    
    /**
     *  Supply account information string to the server. This can be
     *  used for a variety of purposes - for example, the server could
     *  indicate that a password has expired (by sending 332 in reply to
     *  PASS) and a new password automatically supplied via ACCT. It
     *  is up to the server how it uses this string.
     *
     *  @param   accountInfo    account information string
     */
    public void account(String accountInfo)
        throws IOException, FTPException {
        
        checkConnection(true);
        
        lastReply = control.sendCommand("ACCT " + accountInfo);

        // ok or not implemented
        String[] validCodes = {"230", "202"};
        lastValidReply = control.validateReply(lastReply, validCodes);
    }


    /**
     *  Set up SOCKS v4/v5 proxy settings. This can be used if there
     *  is a SOCKS proxy server in place that must be connected thru.
     *  Note that setting these properties directs <b>all</b> TCP
     *  sockets in this JVM to the SOCKS proxy
     *
     *  @param  port  SOCKS proxy port
     *  @param  host  SOCKS proxy hostname
     */
    public static void initSOCKS(String port, String host) {
        Properties props = System.getProperties();
        props.put(SOCKS_PORT, port);
        props.put(SOCKS_HOST, host);
        System.setProperties(props);
    }

    /**
     *  Set up SOCKS username and password for SOCKS username/password
     *  authentication. Often, no authentication will be required
     *  but the SOCKS server may be configured to request these.
     *
     *  @param  username   the SOCKS username
     *  @param  password   the SOCKS password
     */
    public static void initSOCKSAuthentication(String username,
                                               String password) {
        Properties props = System.getProperties();
        props.put("java.net.socks.username", username);
        props.put("java.net.socks.password", password);
        System.setProperties(props);
    }
    
    /**
     * Clear SOCKS settings. Note that setting these properties affects 
     * <b>all</b> TCP sockets in this JVM
     */
    public static void clearSOCKS() {
        
        Properties prop = System.getProperties(); 
        prop.remove(SOCKS_HOST); 
        prop.remove(SOCKS_PORT); 
        System.setProperties(prop); 
    }

    /**
     *  Get the name of the remote host
     *
     *  @return  remote host name
     */
    String getRemoteHostName() {
        return control.getRemoteHostName();
    }

    /**
     *  Issue arbitrary ftp commands to the FTP server.
     *
     *  @param command     ftp command to be sent to server
     *  @param validCodes  valid return codes for this command. If null
     *                      is supplied no validation is performed
     * 
     *  @return  the text returned by the FTP server
     */
    public String quote(String command, String[] validCodes)
        throws IOException, FTPException {
    	
    	checkConnection(true);
    	
        lastReply = control.sendCommand(command);

        // allow for no validation to be supplied
        if (validCodes != null) {
            lastValidReply = control.validateReply(lastReply, validCodes);
        }
        else { // no validation
            lastValidReply = lastReply; // assume valid
        }
        return lastValidReply.getReplyText();       
    }
    
    /**
     *  Issue arbitrary ftp commands to the FTP server.
     *
     *  @param command     ftp command to be sent to server
     *  @return  the raw text returned by the FTP server including reply code
     */
    public String quote(String command)
        throws IOException, FTPException {
        
        checkConnection(true);
        
        lastValidReply = control.sendCommand(command);        
        return lastValidReply.getRawReply();   
    }
    
    /*
     *  (non-Javadoc)
     * @see com.enterprisedt.net.ftp.FTPClientInterface#exists(java.lang.String)
     */
    public boolean exists(String remoteFile) throws IOException, FTPException {
        checkConnection(true);
        
        // first try the SIZE command
        if (sizeSupported)
        {
            lastReply = control.sendCommand("SIZE " + remoteFile);
            char ch = lastReply.getReplyCode().charAt(0);
            if (ch == '2')
                return true;
            if (ch == '5' && fileNotFoundStrings.matches(lastReply.getReplyText()))
                return false;
                
            sizeSupported = false;
            log.debug("SIZE not supported - trying MDTM");
        }

        // then try the MDTM command
        if (mdtmSupported)
        {
            lastReply = control.sendCommand("MDTM " + remoteFile);
            char ch = lastReply.getReplyCode().charAt(0);
            if (ch == '2')
                return true;
            if (ch == '5' && fileNotFoundStrings.matches(lastReply.getReplyText()))
                return false;
             
            mdtmSupported = false;
            log.debug("MDTM not supported - trying RETR");
        }

        // ok, now try RETR since nothing else is supported
        ServerSocket sock = new ServerSocket(0);
        short port = (short)sock.getLocalPort();
        sock.close();
        control.sendPORTCommand(port);
        
        // send the retrieve command
        lastReply = control.sendCommand("RETR " + remoteFile);
        char ch = lastReply.getReplyCode().charAt(0);
        
        // normally return 125 etc. But could return 425 unable to create data
        // connection, which means the file exists but can't connect to our (non-
        // existent) server socket
        if (ch == '1' || ch == '2' || ch == '4')
            return true;
        if (ch == '5' && fileNotFoundStrings.matches(lastReply.getReplyText()))
            return false;
        
        String msg = "Unable to determine if file '" + remoteFile + "' exists.";
        log.warn(msg);
        throw new FTPException(msg);
    }
    
    
    /**
     * Read reply from control socket
     * 
     * @return
     * @throws IOException
     */
    FTPReply readReply() throws IOException {
        return control.readReply();
    }
    
    /**
     * Get the PASV address string (including port numbers)
     * @param pasvReply
     * @return
     */
    String getPASVAddress(String pasvReply) {
        int start = -1;
        int i = 0;
        while (i < pasvReply.length()) {
            if (Character.isDigit(pasvReply.charAt(i))) {
                start = i;
                break;
            }
            i++;
        }
        int end = -1;
        i = pasvReply.length() -1;
        while (i >= 0) {
            if (Character.isDigit(pasvReply.charAt(i))) {
                end = i;
                break;
            }
            i--;
        }
        if (start < 0 || end < 0)
            return null;
        
        return pasvReply.substring(start, end+1);
    }
    
    /**
     * Send a command to the server and get the reply
     * @param command   command
     * @return FTPReply
     * @throws IOException
     */
    public FTPReply sendCommand(String command) throws IOException  {
        return control.sendCommand(command);
    }
    
    /**
     * Validate an FTPReply 
     * 
     * @param reply         reply object
     * @param expectedReplyCode  expected code
     * @throws FTPException
     */
    public void validateReply(FTPReply reply, String expectedReplyCode) throws FTPException {
        control.validateReply(reply, expectedReplyCode);
    }
    
    /**
     * Validate an FTPReply 
     * 
     * @param reply         reply object
     * @param expectedReplyCodes  expected codes
     * @throws FTPException
     */
    public void validateReply(FTPReply reply, String[] expectedReplyCodes) throws FTPException {
        control.validateReply(reply, expectedReplyCodes);
    }

    /*
     *  (non-Javadoc)
     * @see com.enterprisedt.net.ftp.FTPClientInterface#size(java.lang.String)
     */
     public long size(String remoteFile)
         throws IOException, FTPException {
     	
     	 checkConnection(true);
     	
         lastReply = control.sendCommand("SIZE " + remoteFile);
         lastValidReply = control.validateReply(lastReply, "213");

         // parse the reply string .
         String replyText = lastValidReply.getReplyText();
         
         // trim off any trailing characters after a space, e.g. webstar
         // responds to SIZE with 213 55564 bytes
         int spacePos = replyText.indexOf(' ');
         if (spacePos >= 0)
             replyText = replyText.substring(0, spacePos);
         
         // parse the reply
         try {
             return Long.parseLong(replyText);
         }
         catch (NumberFormatException ex) {
             throw new FTPException("Failed to parse reply: " + replyText);
         }         
     }
     
     /*
      *  (non-Javadoc)
      * @see com.enterprisedt.net.ftp.FTPClientInterface#resume()
      */
     public void resume() throws FTPException {
         if (transferType.equals(FTPTransferType.ASCII))
             throw new FTPException("Resume only supported for BINARY transfers");
         resume = true;
         log.info("Resume=true");
     }
     
     /*
      *  (non-Javadoc)
      * @see com.enterprisedt.net.ftp.FTPClientInterface#cancelResume()
      */
     public void cancelResume() 
         throws IOException, FTPException {
         restart(0);
         resume = false;
     }
     
     /**
      * Force the resume flag off. Internal use only.
      */
     protected void forceResumeOff() {
         resume = false;
     }
     
     /**
      * Issue the RESTart command to the remote server. This indicates the byte
      * position that REST is performed at. For put, bytes start at this point, while
      * for get, bytes are fetched from this point.
      * 
      * @param size     the REST param, the mark at which the restart is 
      *                  performed on the remote file. For STOR, this is retrieved
      *                  by SIZE
      * @throws IOException
      * @throws FTPException
      */
     public void restart(long size) 
         throws IOException, FTPException {
         lastReply = control.sendCommand("REST " + size);
         lastValidReply = control.validateReply(lastReply, "350");
     }

     /*
      *  (non-Javadoc)
      * @see com.enterprisedt.net.ftp.FTPClientInterface#put(java.lang.String, java.lang.String)
      */
    public String put(String localPath, String remoteFile)
        throws IOException, FTPException {

        return put(localPath, remoteFile, false);
    }

    /*
     *  (non-Javadoc)
     * @see com.enterprisedt.net.ftp.FTPClientInterface#put(java.io.InputStream, java.lang.String)
     */
    public String put(InputStream srcStream, String remoteFile)
        throws IOException, FTPException {

        return put(srcStream, remoteFile, false);
    }


    /*
     *  (non-Javadoc)
     * @see com.enterprisedt.net.ftp.FTPClientInterface#put(java.lang.String, java.lang.String, boolean)
     */
    public String put(String localPath, String remoteFile, boolean append)
        throws IOException, FTPException {
    	    	
        InputStream srcStream = new FileInputStream(localPath);
        return put(srcStream, remoteFile, append);
     }

    /*
     *  (non-Javadoc)
     * @see com.enterprisedt.net.ftp.FTPClientInterface#put(java.io.InputStream, 
     *  java.lang.String, boolean)
     */
    public String put(InputStream srcStream, String remoteFile, boolean append)
        throws IOException, FTPException {

        FTPTransferType previousType = transferType;
        chooseTransferMode(remoteFile);
        boolean resetMode = true;
        Exception e = null;
        try {        
            if (monitorEx != null)
                monitorEx.transferStarted(TransferDirection.UPLOAD, remoteFile);   
            remoteFile = putData(srcStream, remoteFile, append);
            validateTransfer();
            uploadCount++;
        }
        catch (FTPException ex) {
            e = ex;
            throw ex;
        }
        catch (IOException ex) {
            e = ex;
            resetMode = false;
            validateTransferOnError(ex);
            throw ex;        
        }
        finally {
            if (monitorEx != null)
                monitorEx.transferComplete(TransferDirection.UPLOAD, remoteFile);   
            if (resetMode)
                resetTransferMode(previousType);
        }
        return remoteFile;
    }

    /**
     * Validate that the put() or get() was successful.  This method is not
     * for general u

⌨️ 快捷键说明

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