Professional Documents
Culture Documents
Requirements: ftp4j Javadocs
Requirements: ftp4j Javadocs
Requirements: ftp4j Javadocs
To run the ftp4j library you need a Java Runtime Environment J2SE v. 1.4 or later.
Installation
Add the ftp4j JAR file to your application classpath, and you'll be automatically enabled to
the use of the ftp4j classes.
Javadocs
Here come the ftp4j javadocs.
Quickstart
The main class of the library is FTPClient (it.sauronsoftware.ftp4j.FTPClient).
client.connect("ftp.host.com");
If the service port is other than the standard 21 (or 990 if FTPS):
client.connect("ftp.host.com", port);
In example:
client.connect("ftp.host.com", 8021);
client.login("carlo", "mypassword");
If no exception is thrown you are now authenticated to the remote server. Otherwise, if the
authentication attempt fails, you receive a it.sauronsoftware.ftp4j.FTPException.
Anonymous authentication, if admitted by the connected service, can be done sending the
username "anonymous" and an arbitrary password (note that some servers require an e-mail
address in place of the password):
client.login("anonymous", "ftp4j");
Do anything you want with the remote FTP service, then disconnect:
client.disconnect(true);
This one sends the FTP QUIT command to the remote server, requesting a legal disconnect
procedure. If you just want to break the connection, without sending any advice to the server,
call:
client.disconnect(false);
The connector for a client instance can be setted with the setConnector() method, obviously
before connecting the remote server:
client.setConnector(anyConnectorYouWant);
If you can connect the remote server only through a proxy, the ftp4j library let you choose
between some other connectors:
HTTPTunnelConnector (it.sauronsoftware.ftp4j.connectors.HTTPTunnelConnector)
This one can connect through a HTTP proxy which supports and permits the
CONNECT method.
FTPProxyConnector (it.sauronsoftware.ftp4j.connectors.FTPProxyConnector)
This one can connect through a FTP proxy, supporting both the SITE and the OPEN
command style for demanding the connection with the remote host. Other kinds of
FTP proxies, such the ones requiring a username@remotehost authentication, can be
used without a specific connector, since they have been intended to be transparent to
the client.
SOCKS4Connector (it.sauronsoftware.ftp4j.connectors.SOCKS4Connector)
This one can connect through a SOCKS 4/4a proxy.
SOCKS5Connector (it.sauronsoftware.ftp4j.connectors.SOCKS5Connector)
This one can connect through a SOCKS 5 proxy.
Since the connector architecture used by ftp4j is a pluggable one, you can always build your
own connector implementing the FTPConnector interface.
If the security is set to SECURITY_FTPS, the default port used by the connect() method
changes to 990.
The client object, by default, negotiates SSL connections using the SSL socket factory
provided by javax.net.ssl.SSLSocketFactory.getDefault(). The default socket factory can be
changed calling the client setSSLSocketFactory() method. An alternative SSLSocketFactory,
for example, can be used to trust every certificate given by the remote host (use it carefully):
import it.sauronsoftware.ftp4j.FTPClient;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
// ...
// ...
client.changeDirectory(newPath);
client.changeDirectory("/an/absolute/one");
client.changeDirectory("relative");
client.changeDirectoryUp();
client.rename("oldname", "newname");
In example, think in the current working directory you have a file called "myfile.txt", and you
want to move it in the sub-directory "myfolder":
client.rename("myfile.txt", "myfolder/myfile.txt");
Deleting files
To delete a remote file call:
client.deleteFile(relativeOrAbsolutePath);
In example:
client.deleteFile("useless.txt");
client.createDirectory("newfolder");
client.deleteDirectory(absoluteOrRelativePath);
In example:
client.deleteDirectory("oldfolder");
Please note that usually FTP servers can delete only empty directories.
The ftp4j library can handle many LIST response formats, building from them a unified
structured object representation of the directory contents. Currently ftp4j can handle:
You can also use a file filter parameter with the list() method, i.e.:
If the connected server declares explicitly to support the special MLSD command, ftp4j will
use it instead of the basic LIST command. MLSD responses, infact, are standard, accurated
and more easily parsable. Unfortunately not all of the servers support this command, and
some of them support it badly. For these reasons the developer can control whether ftp4j
should use the MLSD command by calling the setMLSDPolicy() method of a FTPClient
object. Admitted values are:
FTPClient.MLSD_IF_SUPPORTED
The client will use the MLSD command (instead of LIST) only if the server declares
explicitly its support. This is the default ftp4j behaviour.
FTPClient.MLSD_ALWAYS
The client will always use the MLSD command (instead of LIST), also if it is not
explicitly supported by the server.
FTPClient.MLSD_NEVER
The client will never use the MLSD command (instead of LIST), also if it is explicitly
supported by the server.
For example:
client.setMLSDPolicy(FTPClient.MLSD_NEVER);
java.util.Date md = client.modifiedDate("filename.ext");
To upload:
client.upload(new java.io.File("localFile.ext"));
These are blocking calls: they will return only when the transfer will be completed (or failed,
or aborted). Moreover a synchronization lock is imposed on the client, since only a transfer
per time is permitted in a regular FTP communication. You can handle multiple transfers per
time using several FTPClient objects, each one establishing a separate connection with the
server.
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
While the client is downloading or uploading, the transfer can be aborted by another thread
calling the abortCurrentDataTransfer() method on the same FTPClient object. This one
requires a boolean parameter: true to perform a legal abort procedure (an ABOR command is
sent to the server), false to abruptly close the transfer without advice:
Note that also the list() and the listNames() methods imply a data transfer (the response is
served on a data transfer channel), so the abortCurrentDataTransfer() method can also be
used to interrupt a list procedure.
When a data tranfer is aborted the download(), upload(), list() and listNames() methods die
throwing a FTPAbortedException (it.sauronsoftware.ftp4j.FTPAbortedException).
This one resumes the download operation starting from the 1056th byte of the file. The first
byte transferred will be the 1057th.
Other download() and upload() variants let you work with streams instead of java.io.File
objects. So you can also transfer data from and to a database, a network connection or...
another FTPClient object!
Check the javadocs.
1. The client sends to the server its IP address and a port number.
2. The client asks to the server a data transfer, and it starts listening the port sent before.
3. The server connects the address and the port supplied by the client.
4. The data transfer starts in the new established channel.
The active mode requires that your client could receive incoming connections from the
server. If your client is behind a firewall, a proxy, a gateway or a mix of them, most of the
time that is a problem, since it cannot receive incoming connections from outside. Here
comes the passive data transfer mode:
In passive mode the client connects the server: no incoming connection is required.
With ftp4j you can switch between the active and passive modes calling:
The default value for a ftp4j client passive flag is true: if you never call setPassive(false) your
client will act ever asking the passive mode to the server before every transfer.
In the passive transfer mode, the following system property can be set:
ftp4j.passiveDataTransfer.useSuggestedAddress
Setting this property value to "true", "yes" or "1" (case insensitive) causes the client to
use the address suggested by the server as a positive reply to a PASV command. To
avoid frequently reported NAT problems, infact, ftp4j doesn't trust the IP address
declared by the server. The response to the the PASV command is used only for the
port information, while the address is replaced with the host name used for the initial
connection to the server. By activating this feature the developer can force ftp4j to
trust and use the address supplied by the server every time a passive data transfer is
being negotiated.
In the active transfer mode, the following system properties can be set:
ftp4j.activeDataTransfer.hostAddress
Host address. The client will forward to the server the given address, when the server
is requested to perform a connection to the client. The value should be a valid IPv4
address in the a.b.c.d form. I.e. 178.12.34.167. If the value is not supplied, the client
resolves automatically the system address. But if the client runs in a LAN, connecting
an external server through a router with port-forwarding service for active data
transfers, the auto-detected address could not be the right one. This also should
happen when the system has more network interfaces. By using this system property
this kind of problems can be solved.
ftp4j.activeDataTransfer.portRange
Connection port range. The client will pick a port in the range for the data transfer.
The value must be in the start-stop form. I.e. 6000-7000 means that the client will
pick ports only between the given interval when it will ask the server to perform a
connection. By default no range is specified: that means the client could pick any
available port.
ftp4j.activeDataTransfer.acceptTimeout
A value in milliseconds that will be picked as the connection timeout. If the server
does not connect the client within the given timeout, the transfer is interrupted
throwing a FTPDataTransferException. A value equal to 0 means that no timeout will
be applied. Default value is 30000 (30 seconds).
Start the virtual machine with one or more -Dproperty=value arguments. I.e.:
java -Dftp4j.activeDataTransfer.hostAddress=178.12.34.167
-Dftp4j.activeDataTransfer.portRange=6000-7000
-Dftp4j.activeDataTransfer.acceptTimeout=5000 MyClass
client.setType(FTPClient.TYPE_TEXTUAL);
client.setType(FTPClient.TYPE_BINARY);
client.setType(FTPClient.TYPE_AUTO);
The TYPE_AUTO constant, which is also the default one, let the client pick the type
automatically: a textual transfer will be performed if the extension of the file is between the
ones the client recognizes as textual type markers. File extensions are sniffed through a
FTPTextualExtensionRecognizer (it.sauronsoftware.ftp4j.FTPTextualExtensionRecognizer)
instance. The default extension recognizer, which is an instance of
it.sauronsoftware.ftp4j.recognizers.DefaultTextualExtensionRecognizer, recognizes these
extensions as textual ones:
client.setTextualExtensionRecognizer(myRecognizer);
client.setCompressionEnabled(true);
After this call, any subsequent data transfer (downloads, uploads and list operations) will be
compressed, saving bandwidth.
client.setCompressionEnabled(false);
Please note that compressed data transfer will take place only if compression is both
supported and enabled.
By default, compression is disabled, even if supported by the server. If required, it has to be
explicitly turned on.
client.noop();
Automatic NOOPs can also be issued by the client when an inactivity timeout occurs. By
default this feature is disabled. It can be enabled by setting the timeout duration with the
setAutoNoopTimeout() method, supplying a value expressed in milliseconds. For example:
client.setAutoNoopTimeout(30000);
With this value, the client will issue a NOOP command after 30 seconds of inactivity.
The automatic NOOP timeout can be disabled again by using a value equal or less than zero:
client.setAutoNoopTimeout(0);
Exceptions handling
The ftp4j library defines five kinds of exception:
FTPException (it.sauronsoftware.ftp4.FTPException)
Depending on the method, this one is thrown to report a FTP failure. You can check
the reported error code, testing it against the FTPCodes constants to gain more details
about the reason of the failure.
FTPIllegalReplyException (it.sauronsoftware.ftp4.FTPIllegalReplyException)
This one means that the remote server has replied in an illegal way, that is not FTP
compliant. That should be very rare.
FTPListParseException (it.sauronsoftware.ftp4.FTPListParseException)
This one is thrown by the list() method if the response sent by the server cannot be
parsed through the list parsers known by the client.
FTPDataTransferException (it.sauronsoftware.ftp4.FTPDataTransferException)
This one is thrown if a data transfer (download, upload, but also list and listNames)
fails due to a network connection error.
FTPAbortedException (it.sauronsoftware.ftp4.FTPAbortedException)
This one is thrown if a data transfer (download, upload, but also list and listNames)
fails due to a client abort request.