Upload a file from the FTP server in Java
Using The Apache Commons Net API, it is easy to code a program for downloading a file from an FTP server. In this article, you will learn how to properly implement java code to download files from the server via the FTP.
Apache Commons Net API and FTP
The org.apache.commons.net.ftp.FTPClient provides two methods for downloading files from the FTP server:
1) boolean retrieveFile(String remote, OutputStream local): This method retrieves the file from the server by specifying its path in the parameter remote, and writes the retrieved bytes using a OutputStream. This method returns true if successful, otherwise false. This method is suitable with our program when you don't need to know the information about the transfer and how the file is saved to disk. At the end of the download, we must close the output stream OutputStream at the end of the download.
2) InputStream retrieveFileStream(String remote): This method only takes the remote file path as a parameter and does not need a OutputStream, but it returns a InputStream which can be useful for reading the bytes received from the file. This method gives us more control over how bytes are written to the local disk. There are two important points about using this method:
- The completePendingCommand() must be called to complete the download and check the returned value to see if the download has taken place.
- The playback stream must be closed InputStream.
The question is which method should be used? Here are some tricks:
- The first method is the easiest way to download a remote file by passing an argument OutputStream of the file we want to save to disk.
- The second method gives us more control over how the transfer is done, so it requires more code to write by creating a InputStream to read the received bytes and a OutputStream to save the bytes read. This method is useful if you want to know how many bytes have been transferred and how many are left. The Method completePendingCommand() must be called to complete the download.
- Both methods raise an exception IOException or one of these two exceptions: FTPConnectionClosedExcception and CopyStreamException. Therefore, make sure that you handle these exceptions properly when invoking the .
In addition, the following two methods must be called before the methods retrieveFile() and retrieveFileStream():
- void enterLocalPassiveMode(): This method changes the connection mode from server-to-client to client-to-server, which avoids the firewall ban issue.
- void setFileType(int fileType): this method changes the type of file to be transferred, it is recommended to change the type to FTP. BINARY_FILE_TYPE, rather than FTP. ASCII_FILE_TYPE even if it's a text file.
Steps to download a file in Java
Here are the steps to properly implement the download code for a remote file from the FTP server using the Apache Commons Net:
- Connect and log in to the server.
- Use passive connection mode.
- Change the transfer type to binary.
- Create a outputStream to save the downloaded file to disk.
- Specify the recording path to disk.
- If you use the retriveFile():
- Pass outputStream and the file path as arguments.
- Close Write Stream outputStream.
- Read the value returned to check if the download was successful.
- If you use the retriveFileStream():
- Retrieve On InputStream Returned by the method retriveFileStream().
- Create a byte array (buffer) of a set size (typically 4096) to read bytes and write them with a outputStream.
- Call the method completePendingCommand() to complete the download and check the returned value to see if the transfer was successful.
- Close read and write streams InputStream and outputStream.
- Disconnect from the server with the disconnect().
Program for uploading a file with FTP in Java
This code shows how to download a file from the FTP server using these two methods:- boolean retrieveFile(String remote, InputStream local)
- inputStream retrieveFileStream(String remote)
import java.io.BufferedOutputStream;Executing this code indicates that the download has been successful:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FTPDownloadFile {
public static void main(String[] args) {
Server String = "ServerAddress";
int port = 21;
String username = "YourUserName";
String password = "yourPassword";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(username, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP. BINARY_FILE_TYPE);
// Approach 1: Uploading a file using InputStream
File file = new File("plugins and styles.txt");
String FileName = "plugins and styles.txt";
InputStream inputStream = new FileInputStream(file);
System.out.println("Start download");
//download result
boolean res = ftpClient.storeFile(filename, inputStream);
//close the playback stream
inputStream.close();
if (res==true) {
System.out.println("The file "+FileName+
" has been successfully downloaded");
}
// Approach 2: Upload a file using OutputStream
String FileName2 = "Track 2.mp3";
String RemoteFilePath = "/songs/"+FileName2;
File filelocal = new File("C:/Track 2.mp3");
// list the folder where the file is located and
// then search for it with the name to obtain
// its size which will be used to calculate
// the ratio of the download
FTPFile[] files1 = ftpClient.listFiles("/songs");
long size = 0;
for(int i = 0; i< files1.length; i++){
if(files1[i].getName().equals(FileName2))
//get file size
size = files1[i].getSize();
}
OutputStream outputStream2 = new BufferedOutputStream(
new FileOutputStream(local file));
InputStream inputStream2 = ftpClient.retrieveFileStream(
RemoteFilePath);
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
//as long as we haven't reached the end
int transferred = 0;
int percent = 0;
while ((bytesRead = inputStream2.read(bytesArray)) != -1) {
//bytes are written to the specified location
outputStream2.write(bytesArray, 0, bytesRead);
forwarded += bytesRead;
percent = (int) (transferred*100/size);
System.out.println(percentage+"%");
}
//close write read streams
inputStream2.close();
outputStream2.close();
//br //
res = ftpClient.completePendingCommand();
if (res) {
System.out.println("The file "+FileName2+
" has been successfully downloaded");
}
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
//close FTP
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Start download
The plugins and styles.txt file has been downloaded successfully
Start download
1%
2%
3%
.
.
98%
99%
99%
100%
2.mp3 Track file has been downloaded successfully