How to Download and Upload a File in Java Using Ftp

To write Coffee lawmaking that uploads a file from local computer to a remote FTP server, the Apache Eatables Net API is a preferred selection of developers. Information technology has simple and comprehensive API that makes coding with upload files to FTP server with ease.

Table of Content:

    1. Apache Commons Net API for uploading files by FTP protocol
    2. The proper steps to upload a file
    3. Sample program code
    4. Download Apache Commons Internet API

i. Apache Commons Net API for uploading files by FTP protocol

 The FTPClient class provides half dozen storeXXX()methods for transferring a local file to a remote server via FTP protocol:

    • boolean storeFile(String remote, InputStream local)
    • OutputStream storeFileStream(String remote)
    • boolean storeUniqueFile(InputStream local)
    • boolean storeUniqueFile(String remote, InputStream local)
    • OutputStream storeUniqueFileStream()
    • OutputStream storeUniqueFileStream(String remote)

Sounds likewise much? What is the difference among these methods? When to use which one? Well, they tin exist categorized by the following means:

    • Store files by providing an InputStream of the local file (those methods which have an InputStream as a parameter). This type of methods can be used when we don't care how the bytes are transferred from the local file to the remote one, only let the arrangement done the ins and outs.
    • Store files by writing to an OutputStream of the connection (those methods which return an OutputStream). This blazon of methods is needed when we want to control how the bytes are transferred, by writing our own code for reading bytes from the local file and write these bytes to the remote file through the OutputStream object. This can be useful if nosotros want to show progress of the upload, past calculating how many bytes are transferred over full bytes needed.

The two ways higher up can exist used in combination with:

    • Name the remote file explicitly (those methods which accept a String parameter called remote).
    • Allow the server names the remote file with a unique name (those methods which do not have a String parameter).

Despite somewhat intricate of the storeXXX() methods, in that location are only two methods which are mostly used in practice, they are:

    • boolean storeFile(String remote, InputStream local)
    • OutputStream storeFileStream(Cord remote)

Besides the storeXXX() methods, at that place are also 2 other ones need to be invoked before and after a file transfer:

    • boolean setFileType(int fileType): determines which file blazon, either FTP.ASCII_FILE_TYPE or FTP.BINARY_FILE_TYPE, is used for file transfer. The default type is ASCII (plain text file), only it should be ready to binary type in order to piece of work with whatever files. This method must be called earlier a file transfer starts.
    • boolean completePendingCommand(): This method should be called later file transfer finishes, to complete the transaction entirely. It would return truthful if successfully completed, or false otherwise. Nosotros should check return value of this method to ensure the upload is actually successful. However, this method may not be necessary for some of storeXXX() methods.

IMPORTANCES : Past default, the FTP protocol establishes a information connectedness by opening a port on the client and allows the server connecting to this port. This is chosen local agile style, only it is unremarkably blocked by firewall and then the file transfer may not piece of work. Fortunately, the FTP protocol has some other mode, local passive mode, in which a information connection is made past opening a port on the server for the client to connect – and this is not blocked by firewall.

And so information technology is recommended to switch to local passive mode before transferring data, past invoking the method enterLocalPassiveMode() of the FTPClient class.

2. The proper steps to upload a file to FTP server

 To properly write code to upload files to a FTP server using Apache Commons Net API, the following steps should be followed:

    • Connect and login to the server.
    • Enter local passive way for data connection.
    • Prepare file blazon to be transferred to binary.
    • Create an InputStream for the local file.
    • Construct path of the remote file on the server. The path can be absolute or relative to the current working directory.
    • Phone call 1 of the storeXXX()methods to begin file transfer. In that location are two scenarios:
      •       Using an InputStream-based approach: this is the simplest style, since nosotros let the system does the ins and outs. At that place is no additional code, simply passing the InputStream object into the advisable method, such as storeFile (String remote, InputStream local) method.
      •       Using an OutputStream-based approach: this is more circuitous manner, but more control. Typically we have to write some code that reads bytes from the InputStream of the local file and writes those bytes into the OutputStream which is returned past the storeXXX() method, such every bit storeFileStream (String remote) method.
    • Close the opened InputStream and OutputStream.
    • Call completePendingCommand() method to complete transaction.
    • Logout and disconnect from the server.

NOTES: nosotros should cheque render value of the storeXXX() and completePendingCommand() method to ensure the upload is completed successfully.

3. Java FTP File Upload Sample programme lawmaking

 The following sample programme demonstrates uploading local files to a FTP server using these two methods:

    • boolean storeFile(String remote, InputStream local)
    • OutputStream storeFileStream(String remote)

After the storeFile() method, it is not necessary to telephone call the completePendingCommand() method. Hither is the total source code:

import java.io.File; import coffee.io.FileInputStream; 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;  /**  * A program that demonstrates how to upload files from local calculator  * to a remote FTP server using Apache Commons Net API.  * @author www.codejava.cyberspace  */ public class FTPUploadFileDemo {  	public static void chief(String[] args) { 		String server = "www.myserver.com"; 		int port = 21; 		String user = "user"; 		String pass = "pass";  		FTPClient ftpClient = new FTPClient(); 		endeavor {  			ftpClient.connect(server, port); 			ftpClient.login(user, pass); 			ftpClient.enterLocalPassiveMode();  			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  			// Arroyo #1: uploads first file using an InputStream 			File firstLocalFile = new File("D:/Test/Projects.zip");  			String firstRemoteFile = "Projects.zip"; 			InputStream inputStream = new FileInputStream(firstLocalFile);  			Organisation.out.println("Start uploading offset file"); 			boolean done = ftpClient.storeFile(firstRemoteFile, inputStream); 			inputStream.close(); 			if (washed) { 				System.out.println("The first file is uploaded successfully."); 			}  			// Approach #2: uploads 2d file using an OutputStream 			File secondLocalFile = new File("Due east:/Test/Report.medico"); 			String secondRemoteFile = "examination/Study.doc"; 			inputStream = new FileInputStream(secondLocalFile);  			Organisation.out.println("Start uploading second file"); 			OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile); 	        byte[] bytesIn = new byte[4096]; 	        int read = 0;  	        while ((read = inputStream.read(bytesIn)) != -1) { 	        	outputStream.write(bytesIn, 0, read); 	        } 	        inputStream.close(); 	        outputStream.close();  	        boolean completed = ftpClient.completePendingCommand(); 			if (completed) { 				System.out.println("The second file is uploaded successfully."); 			}  		} catch (IOException ex) { 			Organisation.out.println("Error: " + ex.getMessage()); 			ex.printStackTrace(); 		} finally { 			effort { 				if (ftpClient.isConnected()) { 					ftpClient.logout(); 					ftpClient.disconnect(); 				} 			} catch (IOException ex) { 				ex.printStackTrace(); 			} 		} 	}  }

To piece of work with Apache Commons Internet API, the commons-net-VERSION.jar file must exist added to the classpath. The jar file tin can be picked upwardly from within a zip distribution which can be downloaded from http://eatables.apache.org/net/download_net.cgi.

Related Java FTP File Upload Tutorials:

  • Upload files to FTP server using URLConnection course
  • How to upload a directory to a FTP server
  • Swing awarding to upload files to FTP server with progress bar

Other Coffee File Upload Tutorials:

  • Java Servlet File Upload Example
  • Jump MVC File Upload Tutorial
  • Struts File Upload Example
  • Java Upload files to database (Servlet + JSP + MySQL)

Other Java FTP Tutorials:

  • Connect and login to a FTP server
  • Java FTP create directory case
  • Java FTP example - Change working directory
  • Java FTP list files and directories example
  • Java FTP file download tutorial and instance
  • Java FTP delete file example
  • Java FTP example - Search for files and directories

About the Author:

Nam Ha Minh is certified Coffee programmer (SCJP and SCWCD). He started programming with Coffee in the time of Java one.4 and has been falling in love with Java since then. Brand friend with him on Facebook and lookout man his Java videos yous YouTube.

Add comment

trowbridgesuman1992.blogspot.com

Source: https://www.codejava.net/java-se/ftp/java-ftp-file-upload-tutorial-and-example

0 Response to "How to Download and Upload a File in Java Using Ftp"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel