ftpclient.java

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

JAVA
1,527
字号
/* * Copyright 2001-2005 The Apache Software Foundation * * Licensed 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.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import java.util.Vector;import org.apache.commons.net.MalformedServerReplyException;import org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory;import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;import org.apache.commons.net.ftp.parser.ParserInitializationException;import org.apache.commons.net.io.CopyStreamEvent;import org.apache.commons.net.io.CopyStreamException;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 {@link org.apache.commons.net.SocketClient}, * you must first connect to the server with * {@link org.apache.commons.net.SocketClient#connect  connect } * before doing anything, and finally * {@link org.apache.commons.net.SocketClient#disconnect  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: * <pre> *    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); *    } * </pre> * <p> * 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 * {@link org.apache.commons.net.ftp.FTP#getReplyCode  getReplyCode } after * a success or failure. * <p> * The default settings for FTPClient are for it to use * <code> FTP.ASCII_FILE_TYPE </code>, * <code> FTP.NON_PRINT_TEXT_FORMAT </code>, * <code> FTP.STREAM_TRANSFER_MODE </code>, and * <code> FTP.FILE_STRUCTURE </code>.  The only file types directly supported * are <code> FTP.ASCII_FILE_TYPE </code> and * <code> FTP.IMAGE_FILE_TYPE </code> (which is the same as * <code> FTP.BINARY_FILE_TYPE </code>).  Because there are at lest 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 {@link ToNetASCIIOutputStream NetASCII}   * filter streams to provide transparent handling of ASCII files.  We will  * consider incorporating EBCDIC support if there is enough demand. * <p> * <code> FTP.NON_PRINT_TEXT_FORMAT </code>, * <code> FTP.STREAM_TRANSFER_MODE </code>, and * <code> FTP.FILE_STRUCTURE </code> are the only supported formats, * transfer modes, and file structures. * <p> * Because the handling of sockets on different platforms can differ * significantly, the FTPClient automatically issues a new PORT 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 command themselves and dealing with platform * dependent issues. * <p> * 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 * {@link #setRemoteVerificationEnabled setRemoteVerificationEnabled()}. * <p> * 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 * {@link org.apache.commons.net.ftp.FTPReply#SERVICE_NOT_AVAILABLE FTPReply.SERVICE_NOT_AVAILABLE } *  response to a command. * When that occurs, the FTP class method encountering that reply will throw * an {@link org.apache.commons.net.ftp.FTPConnectionClosedException} * . * <code>FTPConnectionClosedException</code> * is a subclass of <code> IOException </code> 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 <code> IOException </code> * catch block.  When you encounter an * {@link org.apache.commons.net.ftp.FTPConnectionClosedException} * , you must disconnect the connection with * {@link #disconnect  disconnect() } to properly clean up the * system resources used by FTPClient.  Before disconnecting, you may check the * last reply code and text with * {@link org.apache.commons.net.ftp.FTP#getReplyCode  getReplyCode }, * {@link org.apache.commons.net.ftp.FTP#getReplyString  getReplyString }, * and * {@link org.apache.commons.net.ftp.FTP#getReplyStrings  getReplyStrings}. * You may avoid server disconnections while the client is idle by * periodicaly sending NOOP commands to the server. * <p> * 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 * {@link 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. * <p> * Listing API Examples * Both paged and unpaged examples of directory listings are available, * as follows: * <p> * Unpaged (whole list) access, using a parser accessible by auto-detect: * <pre> *    FTPClient f=FTPClient(); *    f.connect(server); *    f.login(username, password); *    FTPFile[] files = listFiles(directory); * </pre> * <p> * 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: * <pre> *    FTPClient f=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. *    } * </pre> * <p> * Paged access, using a parser accessible by auto-detect: * <pre> *    FTPClient f=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. *    } * </pre> * <p> * For examples of using FTPClient on servers whose directory listings  * <ul>  * <li>use languages other than English</li> * <li>use date formats other than the American English "standard" <code>MM d yyyy</code></li> * <li>are in different timezones and you need accurate timestamps for dependency checking  *     as in Ant</li> * </ul>see {@link  FTPClientConfig  FTPClientConfig}. * <p> * NOTE: If you experience problems with unwanted firing of <pre>setSoTimeout()</pre>  * during periods of client inactivity, this can be alleviated by calling <pre>setReaderThread(false)</pre>. * For more details, see <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=31122">this thread</a>.  * </p> * <p>  * @author Daniel F. Savarese * @see FTP * @see FTPConnectionClosedException * @see FTPFileEntryParser * @see FTPFileEntryParserFactory * @see DefaultFTPFileEntryParserFactory * @see FTPClientConfig * @see org.apache.commons.net.MalformedServerReplyException **/public class FTPClient extends FTPimplements Configurable{    /***     * 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, __dataTimeout;    private int __passivePort;    private String __passiveHost;    private int __fileType, __fileFormat, __fileStructure, __fileTransferMode;    private boolean __remoteVerificationEnabled;    private long __restartOffset;    private FTPFileEntryParserFactory __parserFactory;    private int __bufferSize;    // __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.    private FTPFileEntryParser __entryParser;        private FTPClientConfig __configuration;    /***     * Default FTPClient constructor.  Creates a new FTPClient instance     * with the data connection mode set to     * <code> ACTIVE_LOCAL_DATA_CONNECTION_MODE </code>, the file type     * set to <code> FTP.ASCII_FILE_TYPE </code>, the     * file format set to <code> FTP.NON_PRINT_TEXT_FORMAT </code>,     * the file structure set to <code> FTP.FILE_STRUCTURE </code>, and     * the transfer mode set to <code> FTP.STREAM_TRANSFER_MODE </code>.     ***/    public FTPClient()    {        __initDefaults();        __dataTimeout = -1;        __remoteVerificationEnabled = true;        __parserFactory = new DefaultFTPFileEntryParserFactory();        __configuration      = null;    }

⌨️ 快捷键说明

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