TechFundu

  • Increase font size
  • Default font size
  • Decrease font size
Welcome Guest,  Login | Join Now
Home Read Articles Java Technologies Core Java FTP Client Implementation in Java

FTP Client Implementation in Java

Last Updated on Thursday, 31 December 2009 10:31
(12 votes, average 4.08 out of 5)

I recently worked on a project where I had to implement a FTP client program in Java. Project requirement was to download a text file from a FTP Server, after that transform that file into an another format that again was a text file and then upload this new transformed text file to another FTP Server. This was the first time that I was working on FTP file download/upload operation in a java program. First task for me was to find a stable Java API for FTP operation and I came across apache foundation’s Jakarta Commons Net project http://commons.apache.org/net/ . Jakarta Commons Net implements the client side of many basic Internet protocols. Currently this library support following protocols:

  • FTP/FTPS
  • NNTP
  • SMTP
  • POP3
  • Telnet
  • TFTP
  • Finger
  • Whois
  • rexec/rcmd/rlogin
  • Time (rdate) and Daytime
  • Echo
  • Discard
  • NTP/SNTP

Now let’s discuss some of the important classes of Jakarta Commons Net library which are required for implementing FTP client program in java:

1.) org.apache.commons.net.SocketClient

SocketClient is an abstract class which provides the basic operations that are required of client objects accessing sockets. It is meant to be subclassed to avoid having to rewrite the same code over and over again to open a socket, close a socket, set timeouts, etc. You can see methods provided by this class on below page.

http://commons.apache.org/net/api/org/apache/commons/net/SocketClient.html

2.) org.apache.commons.net.ftp.FTP

FTP provides the basic the functionality necessary to implement your own FTP client. It extends org.apache.commons.net.SocketClient since extending TelnetClient was causing unwanted behavior (like connections that did not time out properly).

However for most the cases we don’t need to directly use FTP class. The FTPClient class, derived from FTP, implements all the functionality required of an FTP client. The FTP class is made public to provide access to various FTP constants and to make it easier for programmers (or those with special needs) to interact with the FTP protocol and implement their own clients. A set of methods with names corresponding to the FTP command names are provided to facilitate this interaction. You can see methods provided by this class on below page.

http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTP.html

3.) org.apache.commons.net.ftp.FTPClient

FTPClient encapsulates all the functionality necessary to store and retrieve files from an FTP server. This class takes care of all low level details of interacting with an FTP server and provides a convenient higher level interface. You can see methods provided by this class on below page.

http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html

Now let's see a sample program which download a file from FTP server, prints it output on console, transform in output file format and then upload transformed file on another FTP server.

Assumptions:

1.)    This java program uses Java SE 5.0 so Java SE 5.0 or up jars must be in your CLASSPATH.

2.)    You must have FTP server up and running and have access to that.

3.)    Download Jakarta Commons Net library from http://commons.apache.org/downloads/download_net.cgi and put in your CLASSPATH. I am using latest commons-net-2.0.jar for this program.

4.)    This program assumes that you already have an Input text file (Input.txt) on FTP server which you want to download. You can use any free FTP client application like FileZilla to upload your file to FTP server.

package com.techfundu.java;

import java.io.BufferedInputStream;

import java.io.ByteArrayInputStream;

import java.io.InputStream;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPReply;

public class FTPTest {

public void ftpFileDownloadUpload() {

FTPClient ftp1 = null;

FTPClient ftp2 = null;

InputStream is = null;

BufferedInputStream bis = null;

StringBuilder sb = new StringBuilder();

try {

//Created FTPClient Object

ftp1 = new FTPClient();

//Connect with FTP Server

ftp1.connect("FTP Server IP address or host name");

//Pass the credentials of FTP User

ftp1.login("username", "password");        

//Check connection Status                 
System.out.println("Status Check1:" + ftp1.getReplyString());

//Set File Type as Binary
ftp1.setFileType(FTP.BINARY_FILE_TYPE);

//Specify name of file which need to be downloaded. This file should already exist on FTP Server.

String input = "Input.txt";

//Download file now..

is = ftp1.retrieveFileStream(input);

//Read content of file and store in StringBuilder sb

bis = new BufferedInputStream(is);

byte[] b = new byte[8];

int j = bis.read(b);

while(j!=-1) {

byte[] data = new byte[j];

for (int x=0;x < data.length;x++)

{

data[x] = b[x];

}

sb.append(new String(data));

j = bis.read(b);

}

//Print content of file..

System.out.println("Print Input File: \n" + sb.toString());

//Transform content of file into output format

String outputData = transform(sb.toString());

// Connect with FTP Server2, Repeat all steps used for FTP Server1

ftp2 = new FTPClient();

ftp2.connect("FTP Server ip address or hostname");

ftp2.login("username", "password");

System.out.println("Status Check2:" + ftp2.getReplyString());

is = new ByteArrayInputStream(outputData.getBytes());

//Specify Output file name

String output = "Output.txt";

//Upload file to FTP Server2

ftp2.storeFile(output, is);

System.out.println("Status Check3:" + ftp2.getReplyString());

} catch(Throwable t) {

System.out.println("Error in FTP Operation: " + t.getMessage());

} finally {

disconnect(ftp1);

disconnect(ftp2);
}

}

private void disconnect(FTPClient ftp) {

try {

// Logout from the FTP server

ftp.logout();

// Now disconnect from FTP server

if(ftp.isConnected()){

ftp.disconnect();

}

} catch(Exception ex) {

System.out.println("Unable to logout/disconnect from FTP Server. Detail: " + ex.getMessage());

}

}

//Transform input file format to output file format

private String transform(String input){

//Write logic for file transformation.

String output = "This is Output File Text....";

return output;

}

public static void main(String [] args){

FTPTest ftp = new FTPTest();

ftp.ftpFileDownloadUpload();

}          
}

Console Output:

Status Check1:230 User cpgtechdev logged in.

Print Input File:

Input File Text....

Status Check2:230 User cpgtechdev logged in.

Status Check3:226 Transfer complete.


Similar you can try other methods of FTPClient as per your requirement.

We discussed only about FTP in this article but Jakarta Commons Net is much more than FTP. You can look on following classes for other protocols supported by this library. CharGenTCPClient, DaytimeTCPClient, DiscardTCPClient, FingerClient, FTP, NNTP, POP3, RExecClient, SMTP, TelnetClient, TimeTCPClient

 

Written by :
Rajesh Pawar
 
Trackback(0)
Comments (2)Add Comment
Rajesh Pawar
Looks like JDK doesn't provide "full" and "good" support for FTP
written by Rajesh Pawar, January 04, 2010
This is in response to Pravin's comment...
Yes, We can use URLConnection class for FTP but it seems Sun JDK doesn't provide "full" and "good" support for FTP. It is good only for basic operation.There is lot of debate going on this in OpenJDK7 project...Not sure what is the current state of this issue, "seems still in discussion stage", so it is recommended to use Jakarta Commons Net until Sun finalize something clealy on FTP.. Please refer below URLs.

http://blogs.sun.com/jcc/entry/spring_cleaning

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4650689
Pravin Jain
try using URLConnection
written by Pravin Jain, December 31, 2009
I think we can always connect to ftp server using the URLConnection class.
We can use the InputStream and OutputStream available to upload and download the file content.
the URL would also need to include the username and password eg.
ftp://username:password@somehost/path/file

Write comment
You must be logged in to post a comment. Please register if you do not have an account yet.

busy
  Page copy protected against web site content infringement by Copyscape

Follow us on Twitter