FTP upload of file using java

This post is to demonstrate , how to upload the file in FTP location by using java language. This is very simple , and I demonstrate using apache commons-net library. if you are using, maven then you have to add one dependency which I have mentioned below. Or you can download jar file of apache-commons-net and put in project.

I have tested this code in following environemnt:
– JDK 1.7
– Eclipse
– Ubuntu Linux

1. maven dependency for ftp file upload

Maven dependency

1
2
3
4
5
6
 <dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>3.3</version>
      <scope>compile</scope>
    </dependency>

2. Creation of spirng bean for file upload

Spring Bean creation

1
2
3
4
5
6
<bean id="ftpUploadService"	class="com.mysoftkey.service.impl.FtpUploadServiceImpl"	init-method="init">
	<property name="ftpHost" value="${mysoftkey.ftpHost}" />
	<property name="ftpUserId" value="${mysoftkey.ftpuserId}" />
	<property name="ftpPassword" value="${mysoftkey.ftpPassword}" />
	<property name="ftpFolderLocation" value="${mysoftkey.folderLocation}" />
</bean>

File: application.properties

1
2
3
4
mysoftkey.ftpHost=10.xxx.xxx.xx
mysoftkey.ftpuserId=mysoftkey
mysoftkey.ftpPassword=mysoftkey345
mysoftkey.folderLocation=/home/mysoftkey_Test/

3. Java implementation for ftp file upload

This class is holdig some utility function which can be separate out from this as per your requirement.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/**
 * 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 a 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="<meta content='text/html; charset=UTF-8' http-equiv='Content-Type'>"+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;
 }
 
}

Function to store the file in local folder , this is for testing purpose.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * This method is used to store the file in local specified location for
 * testing puporse
 * 
 * @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());
  // e.printStackTrace();
}
 return status;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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;
  }
}

Your comments are welcome to improve this post. Happy Learning 🙂

Leave a Reply

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