FTP upload of file using java

Connect with

ftp upload using javaHow to upload file into FTP server by FTP upload using Java. In this post you will get java code for FTP connection.

1. Overview of FTP upload using Java

This post is about how to upload files in the provided FTP location by using java FTP file upload. This is very simple, and I have used this example of java code for FTP connection for FTP upload using Java. I have used commons-net library for java code for FTP connection and transfer to FTP server.
If you are using, apache maven then you have to add one dependency which I have mentioned below. Or you can download a jar file of apache-commons-net and put it in the project.
I have tested this code in the following environment:
– JDK 1.7
– Eclipse
– Ubuntu Linux

2. maven dependency for FTP upload using Java

You will required jar file so you can use following dependency in your pom.xml for ftp upload in java example.
Maven dependency for java code for ftp connection

<dependency>
     <groupid>commons-net</groupid>
     <artifactid>commons-net</artifactid>
     <version>3.3</version>
     <scope>compile</scope>
   </dependency>

3. Creation of spirng bean for file upload

Spring Bean creation

	
	
	
	

File: application.properties

mysoftkey.ftpHost=10.xxx.xxx.xx
mysoftkey.ftpuserId=mysoftkey
mysoftkey.ftpPassword=mysoftkey345
mysoftkey.folderLocation=/home/mysoftkey_Test/

4. Java FTP file upload

This class is holding some utility function which can be separate out from this as per your requirement. In this java code for FTP connection and FTP file transfer.

File: FtpUploadServiceImpl.java : Java class to upload the file.

/**
 * This service class is used to pull the content by using apache httpConnection
 * and upload the pulled content into specified FTP conention. Source location
 * and traget location is mentioned in the Domain model object.
 * 
 * @author Ranjeet.Jha
 *
 */
public class FtpUploadServiceImpl  {

  private static final Log log = LogFactory.getLog(FtpUploadServiceImpl.class);

  // private HttpClientParams clientParams = new HttpClientParams();
  private static final int httpTimeout = 10000; // 10 sec
  private static final int httpConnectionTimeout = 3000;

  private FtpInfo ftpInfo;

/**
 * This method invoked by init-method hook by spring container.
 */
public void init() {
	this.ftpInfo = new FtpInfo(1, "10.xxx.xx.xxx", "/home/MB.CustomerDocument_Test/", "", "mysoftkey", "FTP_123!@", "2665105");
	
}

@Override
public boolean uploadContentByFTP(FtpInfo ftpInfo, byte[] contentBytes) throws Exception {
  int port = 21;
  InputStream inputStream = null;
  FTPClient ftpClient = new FTPClient();
  boolean uploaded = false;
    try {
	ftpClient.setControlEncoding("UTF-8");
	ftpClient.setConnectTimeout(50000);
	// ftpClient.setSendBufferSize(4096);
	ftpClient.connect(ftpInfo.getServerName(), port);

	if (!ftpClient.isConnected()) {
	  ftpClient.connect(ftpInfo.getServerName(), port);
	}

	// boolean conStatus = ftpClient.login(ftpDtls.getUserid(),
	// ftpDtls.getPassword());
	boolean conStatus = ftpClient.login(ftpInfo.getUserid().trim(), ftpInfo.getPassword());
	if (conStatus) {

	  ftpClient.changeWorkingDirectory(ftpInfo.getFolderLocation()); // home/administrtor/Download/

	  ftpClient.enterLocalPassiveMode();
          // log.debug("buffer size: " +ftpClient.getBufferSize());
	  ftpClient.setBufferSize(51200); // 1024
	  // ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

	  // Creates a directory
	  // String dirToCreate = "/ranjeet1234";
	  showServerReply(ftpClient);

	  // boolean success =
	  // ftpClient.makeDirectory(ftpInfo.getFolderLocation() +
	  // dirToCreate);
	  boolean success = ftpCreateDirectory(ftpClient, ftpInfo.getFolderLocation() + ftpInfo.getFolderToCreate());
	  log.debug("created : " + success);
	  //ftpInfo.setFolderLocation(ftpInfo.getFolderLocation() + "/");
	  log.debug("folderLocation :" + ftpInfo.getFolderLocation());
	  if (success) {
		log.debug("folder created " + ftpInfo.getFolderLocation());
	  }

	  // inputStream = new
	  // ByteArrayInputStream(fileContent.getBytes("UTF-8"));
	  inputStream = new ByteArrayInputStream(contentBytes);
	  // log.debug(" file size : " + fileContent.length());
	  // boolean done = ftpClient.storeFile(ftpDtls.getFileName(),
	  // inputStream);

	  uploaded = ftpClient.storeFile(ftpInfo.getFileName(), inputStream);
          inputStream.close();
	  if (uploaded) {
		log.debug(" file size : " + contentBytes.length + " uploaded");
	  }

	  } else {
		log.error("connection not found for URL : " + ftpInfo.getServerName() + ftpInfo.getFolderLocation());
	  }
	  } catch (ConnectTimeoutException e) {
	  log.error("ConnectTimeoutException caught while connecting , url=" + ftpInfo.getServerName() + ftpInfo.getFolderLocation() + " , msg="
		+ e.getMessage());

	} catch (ConnectException e) {
		log.error("ConnectException caught while connecting , url=" + " , msg=" + e.getMessage());
	} catch (IOException e) {
		log.error("IOException caught while connecting , url=" + " , msg=" + e.getMessage());
		e.printStackTrace();
	} finally {
	disconnect(ftpClient);
		}
		return uploaded;
	}

/**
 * Opens an FTP connection Writes the File to the FTP reading and writing to
 * the Output Stream using character Stream
 * 
 * @param accessDetailsObj , fileContent
 * @return
 * @throws Exception
 */
public void createFilesOnFTP(FtpInfo ftpInfoDtls, String fileContent) throws Exception {
  BufferedReader reader = null;
  FTPClient client = new FTPClient();
  OutputStream os = null;
  OutputStreamWriter out = null;
  // String
  // finalcontent=""+fileContent;
  try {
	Date startTime1 = Calendar.getInstance().getTime();
	Long startTime = new Long(Calendar.getInstance().getTimeInMillis());
	// client.setConnectTimeout(1000);
	client.connect(ftpInfoDtls.getServerName());
	client.login(ftpInfoDtls.getUserid(), ftpInfoDtls.getPassword());
	client.changeWorkingDirectory(ftpInfoDtls.getFolderLocation());
	// client.setSoTimeout(2000);
	// client.setTcpNoDelay(true);
	os = new BufferedOutputStream(client.storeFileStream(ftpInfoDtls.getFileName()));
	out = new OutputStreamWriter(os);
	// out = new OutputStreamWriter(os,"UTF-8");
	out.write(fileContent);
	out.flush();
	out.close();
	os.close();
	client.completePendingCommand();
	Date endTime1 = Calendar.getInstance().getTime();
	Long endTime = new Long(Calendar.getInstance().getTimeInMillis());
	float time = (endTime - startTime);
	// log.info(Thread.currentThread().getName()+
	// " started at "+startTime1+" ,ended at "+endTime1+" and took "+
	// time/1000 + " seconds to complete" );
	System.out.println(Thread.currentThread().getName() + " started at " + startTime1 
		+ " ,ended at " + endTime1 + " and took " + time / 1000 + " seconds to complete FTP process");
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
          client.logout();
	  if (reader != null) {
		try {
		  reader.close();
		} catch (IOException ioe) {
		  ioe.printStackTrace();
		}
	   }
	  }
	}

public static void main(String[] args) {
  try {
    File file = new File("/home/ranjeet/Desktop/TODO.txt");
    byte[] contentBytes = FileUtils.readFileToByteArray(file);
    FtpUploadServiceImpl client = new FtpUploadServiceImpl();
    FtpInfo ftpInfo = new FtpInfo(1, "10.xxx.xx.xxx", "/home/MB.CustomerDocument_Test/", "", "mysoftkey", "FTP_123!@", "2665105");
    client.ftpInfo = ftpInfo;

   ftpInfo.setFileName("1" + "_mysoftkey.txt");
   boolean status = client.uploadContentByFTP(ftpInfo, contentBytes);

 } catch (IOException e) {
	e.printStackTrace();
 } catch (Exception e) {
	e.printStackTrace();
 }
}

private String getContentByInputStream(InputStream is) throws IOException, UnsupportedEncodingException {
  String outData;
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  byte[] byteArray = new byte[1024];
 int count = 0;
  while ((count = is.read(byteArray, 0, byteArray.length)) > 0) {
	outputStream.write(byteArray, 0, count);
  }
  outData = new String(outputStream.toByteArray(), "UTF-8");

  if (outputStream != null) {
	outputStream.close();
	outputStream = null;
   }
  return outData;
}

/**
 * @param ftp
 */
public static void disconnect(FTPClient ftp) {
  if (ftp.isConnected()) {
    try {
	ftp.logout();
	ftp.disconnect();
    } catch (IOException e) {
	// do nothing as file is already saved to server
	log.error("IOException caught while connecting , url=" + " , msg=" + e.getMessage());
    }
  }
}

private static void showServerReply(FTPClient ftpClient) {
  String[] replies = ftpClient.getReplyStrings();
  if (replies != null && replies.length > 0) {
     for (String aReply : replies) {
	System.out.println("SERVER: " + aReply);
     }
  }
}

/**
 * utility to create an arbitrary directory hierarchy on the remote ftp
 * server
 * 
 * @param client
 * @param dirTree
 *            the directory tree only delimited with / chars. No file name!
 * @throws Exception
 */
private static boolean ftpCreateDirectory(FTPClient client, String dirTree) throws IOException {

  boolean dirExists = true;
  if (dirExists) {
    dirExists = client.changeWorkingDirectory(dirTree);
  }
  if (!dirExists) {
	if (!client.makeDirectory(dirTree)) {
	  throw new IOException("Unable to create remote directory '" + dirTree + "'.  error='" + client.getReplyString() + "'");
	}
	if (!client.changeWorkingDirectory(dirTree)) {
	  throw new IOException("Unable to change into newly created remote directory '" + dirTree + "'.  error='" + client.getReplyString() + "'");
	}
  }
 return dirExists;
 }

}

DTO (Data Transfer Object) for FTPInfo

In this example of FTP file upload java we need model class for java code for FTP connection information and FTP server file transfer.

package com.mysoftkey.ftp;

import java.io.Serializable;

/**
 * This is VO ( value object) for ftp details.
 * 
 * @author Ranjeet Jha
 *
 */
public class FtpInfo implements Serializable {

  private String ftpHost;
  private String ftpFolderLocation;
  private String ftpUserId;
  private String ftpPassword;
	
  public void setFtpHost(String ftpHost) {
	this.ftpHost = ftpHost;
  }

  public void setFtpFolderLocation(String ftpFolderLocation) {
	this.ftpFolderLocation = ftpFolderLocation;
  }

  public void setFtpUserId(String ftpUserId) {
    this.ftpUserId = ftpUserId;
  }

  public void setFtpPassword(String ftpPassword) {
   this.ftpPassword = ftpPassword;
  }

  public String getFtpHost() {
	return ftpHost;
  }

  public String getFtpFolderLocation() {
	return ftpFolderLocation;
  }

 public String getFtpUserId() {
	return ftpUserId;
  }

  public String getFtpPassword() {
   return ftpPassword;
  }
}

upload file to application server

This java code for uploading a file into a specified application service location.
Function to store the file in local folder , this is for testing purpose.

/**
 * This method is used to store the file in a local specified location for
 * testing purpose
 * 
 * @param netstorageInfo
 * @param fileConent
 * @return
 */
public boolean writeFileInLocalFileSystem(FtpInfo netstorageInfo, String fileConent) {
 String fileLocation = "D:/opt/LiveBlog";
 boolean status = false;
 try {

 String fileName = fileLocation + netstorageInfo.getFolderLocation() + "/" + netstorageInfo.getFileName();

 File file = new File(fileName);

  // if file doesnt exists, then create it
 if (!file.exists()) {
	file.createNewFile();
  }

  FileWriter fw = new FileWriter(file.getAbsoluteFile());
  BufferedWriter bw = new BufferedWriter(fw);
  bw.write(fileConent);
  bw.close();

  log.debug("Done : {} ", fileName);

} catch (IOException e) {
  log.error("Exception raised while writing in local file : {} ", e.getMessage());
 
}
 return status;
}

Reference

You can visit for more details for Oracle Java Official site

Thanks for visiting this page for java code for ftp connection or FTP upload in java.
Happy Learning 🙂 for Java FTP file upload with me. you can visit How to Sort Objects By Using Comparator in Java.
Your comments are welcome to improve this post. Happy Learning! 🙂


Connect with

Leave a Comment

Your email address will not be published. Required fields are marked *