|
|||||||||
| Home >> All >> org >> apache >> commons >> net >> [ ftp overview ] | PREV CLASS NEXT CLASS | ||||||||
SUMMARY: JAVADOC | SOURCE | DOWNLOAD | NESTED | FIELD | CONSTR | METHOD |
DETAIL: FIELD | CONSTR | METHOD | ||||||||
org.apache.commons.net.ftp
Class FTPClient

java.lang.Objectorg.apache.commons.net.SocketClient
org.apache.commons.net.telnet.Telnet
org.apache.commons.net.telnet.TelnetClient
org.apache.commons.net.ftp.FTP
org.apache.commons.net.ftp.FTPClient
- All Implemented Interfaces:
- Configurable
- public class FTPClient
- extends FTP
- implements Configurable
- extends FTP
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 55 before doing anything, and finally disconnect 55 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:
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 55 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.IMAGE_FILE_TYPE (which is the same as
FTP.BINARY_FILE_TYPE ). 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 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 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.
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() 55 .
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 55
response to a command.
When that occurs, the FTP class method encountering that reply will throw
an 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
FTPConnectionClosedException
, you must disconnect the connection with
disconnect() 55 to properly clean up the
system resources used by FTPClient. Before disconnecting, you may check the
last reply code and text with
getReplyCode 55 ,
getReplyString 55 ,
and
getReplyStrings 55 .
You may avoid server disconnections while the client is idle by
periodicaly 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=FTPClient();
f.connect(server);
f.login(username, password);
FTPFile[] files = 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=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=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
NOTE: If you experience problems with unwanted firing of
setSoTimeout()during periods of client inactivity, this can be alleviated by calling
setReaderThread(false). For more details, see this thread.
| Field Summary | |
private int |
__bufferSize
|
private FTPClientConfig |
__configuration
|
private int |
__dataConnectionMode
|
private int |
__dataTimeout
|
private FTPFileEntryParser |
__entryParser
|
private int |
__fileFormat
|
private int |
__fileStructure
|
private int |
__fileTransferMode
|
private int |
__fileType
|
private org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory |
__parserFactory
|
private java.lang.String |
__passiveHost
|
private int |
__passivePort
|
private boolean |
__remoteVerificationEnabled
|
private long |
__restartOffset
|
private java.lang.String |
__systemName
|
static int |
ACTIVE_LOCAL_DATA_CONNECTION_MODE
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. |
static int |
ACTIVE_REMOTE_DATA_CONNECTION_MODE
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. |
static int |
PASSIVE_LOCAL_DATA_CONNECTION_MODE
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. |
static int |
PASSIVE_REMOTE_DATA_CONNECTION_MODE
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. |
| Fields inherited from class org.apache.commons.net.ftp.FTP |
_commandSupport_, _controlEncoding, _controlInput, _controlOutput, _newReplyString, _replyCode, _replyLines, _replyString, ASCII_FILE_TYPE, BINARY_FILE_TYPE, BLOCK_TRANSFER_MODE, CARRIAGE_CONTROL_TEXT_FORMAT, COMPRESSED_TRANSFER_MODE, DEFAULT_CONTROL_ENCODING, DEFAULT_DATA_PORT, DEFAULT_PORT, EBCDIC_FILE_TYPE, FILE_STRUCTURE, IMAGE_FILE_TYPE, LOCAL_FILE_TYPE, NON_PRINT_TEXT_FORMAT, PAGE_STRUCTURE, RECORD_STRUCTURE, STREAM_TRANSFER_MODE, TELNET_TEXT_FORMAT |
| Fields inherited from class org.apache.commons.net.telnet.TelnetClient |
readerThread, TERMINAL_TYPE, TERMINAL_TYPE_IS, TERMINAL_TYPE_SEND |
| Fields inherited from class org.apache.commons.net.SocketClient |
_defaultPort_, _input_, _isConnected_, _output_, _socket_, _socketFactory_, _timeout_, NETASCII_EOL |
| Constructor Summary | |
FTPClient()
Default FTPClient constructor. |
|
| Method Summary | |
private void |
__initDefaults()
|
private void |
__parsePassiveModeReply(java.lang.String reply)
|
private java.lang.String |
__parsePathname(java.lang.String reply)
|
private boolean |
__storeFile(int command,
java.lang.String remote,
java.io.InputStream local)
|
private java.io.OutputStream |
__storeFileStream(int command,
java.lang.String remote)
|
protected void |
_connectAction_()
Handles special connection requirements. |
protected java.net.Socket |
_openDataConnection_(int command,
java.lang.String arg)
Establishes a data connection with the FTP server, returning a Socket for the connection if successful. |
boolean |
abort()
Abort a transfer in progress. |
boolean |
allocate(int bytes)
Reserve a number of bytes on the server for the next file transfer. |
boolean |
allocate(int bytes,
int recordSize)
Reserve space on the server for the next file transfer. |
boolean |
appendFile(java.lang.String remote,
java.io.InputStream local)
Appends to a file on the server with the given name, taking input from the given InputStream. |
java.io.OutputStream |
appendFileStream(java.lang.String remote)
Returns an OutputStream through which data can be written to append to a file on the server with the given name. |
boolean |
changeToParentDirectory()
Change to the parent directory of the current working directory. |
boolean |
changeWorkingDirectory(java.lang.String pathname)
Change the current working directory of the FTP session. |
boolean |
completePendingCommand()
There are a few FTPClient methods that do not complete the entire sequence of FTP commands to complete a transaction. |
void |
configure(FTPClientConfig config)
Implementation of the Configurable interface. |
FTPFileList |
createFileList(FTPFileEntryParser parser)
Deprecated. - use initiateListParsing(FTPFileEntryParser) method instead. |
FTPFileList |
createFileList(java.lang.String pathname,
FTPFileEntryParser parser)
Deprecated. - use initiateListParsing(String, FTPFileEntryParser) method instead. |
boolean |
deleteFile(java.lang.String pathname)
Deletes a file on the FTP server. |
void |
disconnect()
Closes the connection to the FTP server and restores connection parameters to the default values. |
void |
enterLocalActiveMode()
Set the current data connection mode to ACTIVE_LOCAL_DATA_CONNECTION_MODE. |
void |
enterLocalPassiveMode()
Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE . |
boolean |
enterRemoteActiveMode(java.net.InetAddress host,
int port)
Set the current data connection mode to ACTIVE_REMOTE_DATA_CONNECTION . |
boolean |
enterRemotePassiveMode()
Set the current data connection mode to PASSIVE_REMOTE_DATA_CONNECTION_MODE . |
int |
getBufferSize()
Retrieve the current internal buffer size. |
int |
getDataConnectionMode()
Returns the current data connection mode (one of the _DATA_CONNECTION_MODE constants. |
java.lang.String |
getPassiveHost()
Returns the hostname or IP address (in the form of a string) returned by the server when entering passive mode. |
int |
getPassivePort()
If in passive mode, returns the data port of the passive host. |
long |
getRestartOffset()
Fetches the restart offset. |
java.lang.String |
getStatus()
Issue the FTP STAT command to the server. |
java.lang.String |
getStatus(java.lang.String pathname)
Issue the FTP STAT command to the server for a given pathname. |
java.lang.String |
getSystemName()
Fetches the system type name from the server and returns the string. |
FTPListParseEngine |
initiateListParsing()
Using the default autodetect mechanism, initialize an FTPListParseEngine object containing a raw file information for the current working directory on the server This information is obtained through the LIST command. |
private FTPListParseEngine |
initiateListParsing(FTPFileEntryParser parser,
java.lang.String pathname)
private method through which all listFiles() and initiateListParsing methods pass once a parser is determined. |
FTPListParseEngine |
initiateListParsing(java.lang.String pathname)
Using the default autodetect mechanism, initialize an FTPListParseEngine object containing a raw file information for the supplied directory. |
FTPListParseEngine |
initiateListParsing(java.lang.String parserKey,
java.lang.String pathname)
Using the supplied parser key, initialize an FTPListParseEngine object containing a raw file information for the supplied directory. |
boolean |
isRemoteVerificationEnabled()
Return whether or not verification of the remote host participating in data connections is enabled. |
FTPFile[] |
listFiles()
Using the default system autodetect mechanism, obtain a list of file information for the current working directory. |
FTPFile[] |
listFiles(FTPFileListParser parser)
Deprecated. use listFiles(String parserKey) instead. |
FTPFile[] |
listFiles(FTPFileListParser parser,
java.lang.String pathname)
Deprecated. use listFiles(String parserKey, String pathname) instead |
FTPFile[] |
listFiles(java.lang.String pathname)
Using the default system autodetect mechanism, obtain a list of file information for the current working directory or for just a single file. |
FTPFile[] |
listFiles(java.lang.String parserKey,
java.lang.String pathname)
Deprecated. use listFiles() 55 or listFiles(String) 55 instead and specify the parser Key in an FTPClientConfig object instead. |
java.lang.String |
listHelp()
Fetches the system help information from the server and returns the full string. |
java.lang.String |
listHelp(java.lang.String command)
Fetches the help information for a given command from the server and returns the full string. |
java.lang.String[] |
listNames()
Obtain a list of filenames in the current working directory This information is obtained through the NLST command. |
java.lang.String[] |
listNames(java.lang.String pathname)
Obtain a list of filenames in a directory (or just the name of a given file, which is not particularly useful). |
boolean |
login(java.lang.String username,
java.lang.String password)
Login to the FTP server using the provided username and password. |
boolean |
login(java.lang.String username,
java.lang.String password,
java.lang.String account)
Login to the FTP server using the provided username, password, and account. |
boolean |
logout()
Logout of the FTP server by sending the QUIT command. |
boolean |
makeDirectory(java.lang.String pathname)
Creates a new subdirectory on the FTP server in the current directory (if a relative pathname is given) or where specified (if an absolute pathname is given). |
java.lang.String |
printWorkingDirectory()
Returns the pathname of the current working directory. |
(package private) boolean |
reinitialize()
Reinitialize the FTP session. |
boolean |
remoteAppend(java.lang.String filename)
Initiate a server to server file transfer. |
boolean |
remoteRetrieve(java.lang.String filename)
Initiate a server to server file transfer. |
boolean |
remoteStore(java.lang.String filename)
Initiate a server to server file transfer. |
boolean |
remoteStoreUnique()
Initiate a server to server file transfer. |
boolean |
remoteStoreUnique(java.lang.String filename)
Initiate a server to server file transfer. |
boolean |
removeDirectory(java.lang.String pathname)
Removes a directory on the FTP server (if empty). |
boolean |
rename(java.lang.String from,
java.lang.String to)
Renames a remote file. |
private boolean |
restart(long offset)
Restart a STREAM_TRANSFER_MODE file transfer starting
from the given offset. |
boolean |
retrieveFile(java.lang.String remote,
java.io.OutputStream local)
Retrieves a named file from the server and writes it to the given OutputStream. |
java.io.InputStream |
retrieveFileStream(java.lang.String remote)
Returns an InputStream from which a named file from the server can be read. |
boolean |
sendNoOp()
Sends a NOOP command to the FTP server. |
boolean |
sendSiteCommand(java.lang.String arguments)
Send a site specific command. |
void |
setBufferSize(int bufSize)
Set the internal buffer size. |
void |
setDataTimeout(int timeout)
Sets the timeout in milliseconds to use when reading from the data connection. |
boolean |
setFileStructure(int structure)
Sets the file structure. |
boolean |
setFileTransferMode(int mode)
Sets the transfer mode. |
boolean |
setFileType(int fileType)
Sets the file type to be transferred. |
boolean |
setFileType(int fileType,
int formatOrByteSize)
Sets the file type to be transferred and the format. |
void |
setParserFactory(org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory parserFactory)
set the factory used for parser creation to the supplied factory object. |
void |
setRemoteVerificationEnabled(boolean enable)
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. |
void |
setRestartOffset(long offset)
Sets the restart offset. |
boolean |
storeFile(java.lang.String remote,
java.io.InputStream local)
Stores a file on the server using the given name and taking input from the given InputStream. |
java.io.OutputStream |
storeFileStream(java.lang.String remote)
Returns an OutputStream through which data can be written to store a file on the server using the given name. |
boolean |
storeUniqueFile(java.io.InputStream local)
Stores a file on the server using a unique name assigned by the server and taking input from the given InputStream. |
boolean |
storeUniqueFile(java.lang.String remote,
java.io.InputStream local)
Stores a file on the server using a unique name derived from the given name and taking input from the given InputStream. |
java.io.OutputStream |
storeUniqueFileStream()
Returns an OutputStream through which data can be written to store a file on the server using a unique name assigned by the server. |
java.io.OutputStream |
storeUniqueFileStream(java.lang.String remote)
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. |
boolean |
structureMount(java.lang.String pathname)
Issue the FTP SMNT command. |
| Methods inherited from class org.apache.commons.net.ftp.FTP |
abor, acct, addProtocolCommandListener, allo, allo, appe, cdup, cwd, dele, getControlEncoding, getReply, getReplyCode, getReplyString, getReplyStrings, help, help, list, list, mkd, mode, nlst, nlst, noop, pass, pasv, port, pwd, quit, rein, removeProtocolCommandListener, rest, retr, rmd, rnfr, rnto, sendCommand, sendCommand, sendCommand, sendCommand, setControlEncoding, site, smnt, stat, stat, stor, stou, stou, stru, syst, type, type, user |
| Methods inherited from class org.apache.commons.net.telnet.TelnetClient |
addOptionHandler, deleteOptionHandler, getInputStream, getLocalOptionState, getOutputStream, getReaderThread, getRemoteOptionState, registerNotifHandler, registerSpyStream, sendAYT, setReaderThread, stopSpyStream, unregisterNotifHandler |
| Methods inherited from class org.apache.commons.net.SocketClient |
connect, connect, connect, connect, connect, connect, getDefaultPort, getDefaultTimeout, getLocalAddress, getLocalPort, getRemoteAddress, getRemotePort, getSoLinger, getSoTimeout, getTcpNoDelay, isConnected, setDefaultPort, setDefaultTimeout, setSocketFactory, setSoLinger, setSoTimeout, setTcpNoDelay, verifyRemote |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
ACTIVE_LOCAL_DATA_CONNECTION_MODE
public static final int ACTIVE_LOCAL_DATA_CONNECTION_MODE
- 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.
- See Also:
- Constant Field Values
ACTIVE_REMOTE_DATA_CONNECTION_MODE
public static final int ACTIVE_REMOTE_DATA_CONNECTION_MODE
- 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.
- See Also:
- Constant Field Values
PASSIVE_LOCAL_DATA_CONNECTION_MODE
public static final int PASSIVE_LOCAL_DATA_CONNECTION_MODE
- 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.
- See Also:
- Constant Field Values
PASSIVE_REMOTE_DATA_CONNECTION_MODE
public static final int PASSIVE_REMOTE_DATA_CONNECTION_MODE
- 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.
- See Also:
- Constant Field Values
__dataConnectionMode
private int __dataConnectionMode
__dataTimeout
private int __dataTimeout
__passivePort
private int __passivePort
__passiveHost
private java.lang.String __passiveHost
__fileType
private int __fileType
__fileFormat
private int __fileFormat
__fileStructure
private int __fileStructure
__fileTransferMode
private int __fileTransferMode
__remoteVerificationEnabled
private boolean __remoteVerificationEnabled
__restartOffset
private long __restartOffset
__parserFactory
private org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory __parserFactory
__bufferSize
private int __bufferSize
__systemName
private java.lang.String __systemName
__entryParser
private FTPFileEntryParser __entryParser
__configuration
private FTPClientConfig __configuration
| Constructor Detail |
FTPClient
public FTPClient()
- Default FTPClient constructor. Creates a new FTPClient instance
with the data connection mode set to
ACTIVE_LOCAL_DATA_CONNECTION_MODE, the file type set toFTP.ASCII_FILE_TYPE, the file format set toFTP.NON_PRINT_TEXT_FORMAT, the file structure set toFTP.FILE_STRUCTURE, and the transfer mode set toFTP.STREAM_TRANSFER_MODE.
| Method Detail |
__initDefaults
private void __initDefaults()
__parsePathname
private java.lang.String __parsePathname(java.lang.String reply)
__parsePassiveModeReply
private void __parsePassiveModeReply(java.lang.String reply) throws org.apache.commons.net.MalformedServerReplyException
__storeFile
private boolean __storeFile(int command,
java.lang.String remote,
java.io.InputStream local)
throws java.io.IOException
__storeFileStream
private java.io.OutputStream __storeFileStream(int command, java.lang.String remote) throws java.io.IOException
_openDataConnection_
protected java.net.Socket _openDataConnection_(int command, java.lang.String arg) throws java.io.IOException
- 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)55 , 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.
_connectAction_
protected void _connectAction_()
throws java.io.IOException
- Description copied from class:
org.apache.commons.net.telnet.TelnetClient - Handles special connection requirements.
- Overrides:
_connectAction_in classFTP
setDataTimeout
public void setDataTimeout(int timeout)
- Sets the timeout in milliseconds to use when reading from the
data connection. This timeout will be set immediately after
opening the data connection.
setParserFactory
public void setParserFactory(org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory parserFactory)
- set the factory used for parser creation to the supplied factory object.
disconnect
public void disconnect()
throws java.io.IOException
- Closes the connection to the FTP server and restores
connection parameters to the default values.
- Overrides:
disconnectin classFTP
setRemoteVerificationEnabled
public void setRemoteVerificationEnabled(boolean enable)
- 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.
isRemoteVerificationEnabled
public boolean isRemoteVerificationEnabled()
- Return whether or not verification of the remote host participating
in data connections is enabled. The default behavior is for
verification to be enabled.
login
public boolean login(java.lang.String username, java.lang.String password) throws java.io.IOException
- Login to the FTP server using the provided username and password.
login
public boolean login(java.lang.String username, java.lang.String password, java.lang.String account) throws java.io.IOException
- 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.
logout
public boolean logout()
throws java.io.IOException
- Logout of the FTP server by sending the QUIT command.
changeWorkingDirectory
public boolean changeWorkingDirectory(java.lang.String pathname) throws java.io.IOException
- Change the current working directory of the FTP session.
changeToParentDirectory
public boolean changeToParentDirectory()
throws java.io.IOException
- Change to the parent directory of the current working directory.
structureMount
public boolean structureMount(java.lang.String pathname) throws java.io.IOException
- Issue the FTP SMNT command.
reinitialize
boolean reinitialize()
throws java.io.IOException
- Reinitialize the FTP session. Not all FTP servers support this
command, which issues the FTP REIN command.
enterLocalActiveMode
public void enterLocalActiveMode()
- 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.
enterLocalPassiveMode
public void enterLocalPassiveMode()
- 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 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 inPASSIVE_LOCAL_DATA_CONNECTION_MODEuntil the mode is changed by calling some other method such as enterLocalActiveMode() 55
enterRemoteActiveMode
public boolean enterRemoteActiveMode(java.net.InetAddress host, int port) throws java.io.IOException
- 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() 55 if you wish to return to the normal data connection mode.
enterRemotePassiveMode
public boolean enterRemotePassiveMode()
throws java.io.IOException
- 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() 55 if you wish to return to the normal data connection mode.
getPassiveHost
public java.lang.String getPassiveHost()
- 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() 55 .
This is because FTPClient sends a PASV command to the server only
just before opening a data connection, and not when you call
enterLocalPassiveMode() 55 .
getPassivePort
public int getPassivePort()
- 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() 55 .
This is because FTPClient sends a PASV command to the server only
just before opening a data connection, and not when you call
enterLocalPassiveMode() 55 .
getDataConnectionMode
public int getDataConnectionMode()
- Returns the current data connection mode (one of the
_DATA_CONNECTION_MODEconstants.
setFileType
public boolean setFileType(int fileType)
throws java.io.IOException
- Sets the file type to be transferred. This should be one of
FTP.ASCII_FILE_TYPE,FTP.IMAGE_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 isFTP.ASCII_FILE_TYPEif this method is never called.
setFileType
public boolean setFileType(int fileType,
int formatOrByteSize)
throws java.io.IOException
- Sets the file type to be transferred and the format. The type should be
one of
FTP.ASCII_FILE_TYPE,FTP.IMAGE_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 isFTP.ASCII_FILE_TYPEif this method is never called. The format should be one of the FTP classTEXT_FORMATconstants, or if the type isFTP.LOCAL_FILE_TYPE, the format should be the byte size for that type. The default format isFTP.NON_PRINT_TEXT_FORMATif this method is never called.
setFileStructure
public boolean setFileStructure(int structure)
throws java.io.IOException
- Sets the file structure. The default structure is
FTP.FILE_STRUCTUREif this method is never called.
setFileTransferMode
public boolean setFileTransferMode(int mode)
throws java.io.IOException
- Sets the transfer mode. The default transfer mode
FTP.STREAM_TRANSFER_MODEif this method is never called.
remoteRetrieve
public boolean remoteRetrieve(java.lang.String filename) throws java.io.IOException
- 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.
remoteStore
public boolean remoteStore(java.lang.String filename) throws java.io.IOException
- 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
remoteRetrieveissued to it by another FTPClient.
remoteStoreUnique
public boolean remoteStoreUnique(java.lang.String filename) throws java.io.IOException
- 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
remoteRetrieveissued to it by another FTPClient.
remoteStoreUnique
public boolean remoteStoreUnique()
throws java.io.IOException
- 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
remoteRetrieveissued 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 ofremoteStoreUnique
remoteAppend
public boolean remoteAppend(java.lang.String filename) throws java.io.IOException
- 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
remoteRetrieveissued to it by another FTPClient.
completePendingCommand
public boolean completePendingCommand()
throws java.io.IOException
- 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); }
retrieveFile
public boolean retrieveFile(java.lang.String remote, java.io.OutputStream local) throws java.io.IOException
- 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.
retrieveFileStream
public java.io.InputStream retrieveFileStream(java.lang.String remote) throws java.io.IOException
- 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 55 and
check its return value to verify success.
storeFile
public boolean storeFile(java.lang.String remote, java.io.InputStream local) throws java.io.IOException
- 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).
storeFileStream
public java.io.OutputStream storeFileStream(java.lang.String remote) throws java.io.IOException
- 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 55 and
check its return value to verify success.
appendFile
public boolean appendFile(java.lang.String remote, java.io.InputStream local) throws java.io.IOException
- 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).
appendFileStream
public java.io.OutputStream appendFileStream(java.lang.String remote) throws java.io.IOException
- 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 55 and
check its return value to verify success.
storeUniqueFile
public boolean storeUniqueFile(java.lang.String remote, java.io.InputStream local) throws java.io.IOException
- 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).
storeUniqueFileStream
public java.io.OutputStream storeUniqueFileStream(java.lang.String remote) throws java.io.IOException
- 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 55 and
check its return value to verify success.
storeUniqueFile
public boolean storeUniqueFile(java.io.InputStream local) throws java.io.IOException
- 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).
storeUniqueFileStream
public java.io.OutputStream storeUniqueFileStream() throws java.io.IOException
- 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 55 and
check its return value to verify success.
allocate
public boolean allocate(int bytes)
throws java.io.IOException
- Reserve a number of bytes on the server for the next file transfer.
allocate
public boolean allocate(int bytes,
int recordSize)
throws java.io.IOException
- Reserve space on the server for the next file transfer.
restart
private boolean restart(long offset)
throws java.io.IOException
- Restart a
STREAM_TRANSFER_MODEfile transfer starting from the given offset. This will only work on FTP servers supporting the REST comand for the stream transfer mode. However, most FTP servers support this. Any subsequent file transfer will start reading or writing the remote file from the indicated offset.
setRestartOffset
public void setRestartOffset(long offset)
- Sets the restart offset. The restart command is sent to the server
only before sending the file transfer command. When this is done,
the restart marker is reset to zero.
getRestartOffset
public long getRestartOffset()
- Fetches the restart offset.
rename
public boolean rename(java.lang.String from, java.lang.String to) throws java.io.IOException
- Renames a remote file.
abort
public boolean abort()
throws java.io.IOException
- Abort a transfer in progress.
deleteFile
public boolean deleteFile(java.lang.String pathname) throws java.io.IOException
- Deletes a file on the FTP server.
removeDirectory
public boolean removeDirectory(java.lang.String pathname) throws java.io.IOException
- Removes a directory on the FTP server (if empty).
makeDirectory
public boolean makeDirectory(java.lang.String pathname) throws java.io.IOException
- Creates a new subdirectory on the FTP server in the current directory
(if a relative pathname is given) or where specified (if an absolute
pathname is given).
printWorkingDirectory
public java.lang.String printWorkingDirectory() throws java.io.IOException
- Returns the pathname of the current working directory.
sendSiteCommand
public boolean sendSiteCommand(java.lang.String arguments) throws java.io.IOException
- Send a site specific command.
getSystemName
public java.lang.String getSystemName() throws java.io.IOException
- Fetches the system type name from the server and returns the string.
This value is cached for the duration of the connection after the
first call to this method. In other words, only the first time
that you invoke this method will it issue a SYST command to the
FTP server. FTPClient will remember the value and return the
cached value until a call to disconnect.
listHelp
public java.lang.String listHelp() throws java.io.IOException
- Fetches the system help information from the server and returns the
full string.
listHelp
public java.lang.String listHelp(java.lang.String command) throws java.io.IOException
- Fetches the help information for a given command from the server and
returns the full string.
sendNoOp
public boolean sendNoOp()
throws java.io.IOException
- Sends a NOOP command to the FTP server. This is useful for preventing
server timeouts.
listNames
public java.lang.String[] listNames(java.lang.String pathname) throws java.io.IOException
- Obtain a list of filenames in a directory (or just the name of a given
file, which is not particularly useful). This information is obtained
through the NLST command. If the given pathname is a directory and
contains no files, a zero length array is returned only
if the FTP server returned a positive completion code, otherwise
null is returned (the FTP server returned a 550 error No files found.).
If the directory is not empty, an array of filenames in the directory is
returned. If the pathname corresponds
to a file, only that file will be listed. The server may or may not
expand glob expressions.
listNames
public java.lang.String[] listNames() throws java.io.IOException
- Obtain a list of filenames in the current working directory
This information is obtained through the NLST command. If the current
directory contains no files, a zero length array is returned only
if the FTP server returned a positive completion code, otherwise,
null is returned (the FTP server returned a 550 error No files found.).
If the directory is not empty, an array of filenames in the directory is
returned.
listFiles
public FTPFile[] listFiles(java.lang.String parserKey, java.lang.String pathname) throws java.io.IOException
- Deprecated. use listFiles() 55 or
listFiles(String) 55 instead and specify the
parser Key in an FTPClientConfig object instead.
- Using the supplied
parserKey, obtain a list of file information for the current working directory or for just a single file.If
keyis null, this object will try to autodetect the system-type/parser-type by calling the SYST command.Under the DefaultFTPFileEntryParserFactory, which is used unless a different factory has been specified, the key can be either a recognized System type for which a parser has been defined, or the fully qualified class name of a class that implements org.apache.commons.net.ftp.FTPFileEntryParser.
This information is obtained through the LIST command. The contents of the ret
- Using the supplied
JAVADOC