The ftp4j library implements a Java full-features FTP client. With ftp4j embedded in your application you can: transfer files (upload and download), browse the remote FTP site (directory listing included), create, delete, rename and move remote directories and files.
The main class of the library is FTPClient (it.sauronsoftware.ftp4j.FTPClient).
Start creating a FTPClient instance:
FTPClient client = new FTPClient();
Connect now to a remote FTP service:
client.connect("ftp.host.com");
If the service port is other than the standard 21:
client.connect("ftp.host.com", port);
In example:
client.connect("ftp.host.com", 8021);
Step now to the login procedure:
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);
Connecting through a proxy
The client connects to the server through a connector (an object implementing the it.sauronsoftware.ftp4j.FTPConnector interface), which returns to the client an already open connection (an object implementing the it.sauronsoftware.ftp4j.FTPConnection interface). That is why ftp4j could support a large set of proxies.
The connector for a client instance can be setted with the setConnector() method, obviously before connecting the remote server:
client.setConnector(anyConnectorYouWant); Browsing the remote site
Get the current directory absolute path calling:
String dir = client.currentDirectory();
Change directory with:
client.changeDirectory(newPath);
You can use both absolute and relative paths:
client.changeDirectory("/an/absolute/one");
client.changeDirectory("relative");
Back to the parent directory with:
client.changeDirectoryUp();
Renaming files and directories
To rename a remote file or directory:
client.rename("oldname", "newname");
Moving files and directories
The rename() method can also be used to move files and directories from a location to another.
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":