Some data exchange needs to be completed through FTP. For FTP clients, Java provides us with powerful class libraries. Common examples include sun.net. FTP. ftpclient and org.apache.commons.net. FTP. ftpclient (provided by Apach ). Both of them are quite useful. In comparison, the latter has better functions. Sun.net. FTP. ftpclient can help us with some simple FTP client functions: Download and upload files. However, there is no way to create directories. We have to use third-party source code, such as com.w.isedt.net. FTP. ftpclient. However, the org.apache.commons.net. FTP. ftpclient features provided by Apach are comprehensive.
The following describes how to use the two methods:
1. Example of sun.net. FTP. ftpclient:
Import java. AWT. borderlayout;
Import java. AWT. flowlayout;
Import java. AWT. gridlayout;
Import java. AWT. List;
Import java. AWT. event. actionevent;
Import java. AWT. event. actionlistener;
Import java. Io .*;
Import javax. Swing. jbutton;
Import javax. Swing. jcombobox;
Import javax. Swing. jframe;
Import javax. Swing. jlabel;
Import javax. Swing. jlist;
Import javax. Swing. joptionpane;
Import javax. Swing. jpanel;
Import javax. Swing. jscrollpane;
Import javax. Swing. jtextfield;
Import javax. Swing. jtoolbar;
Import javax. Swing. defaultlistmodel;
Import javax. Swing. jtree;
Import sun.net. telnetinputstream;
Import sun.net. telnetoutputstream;
Import sun.net. FTP. ftpclient;
Import sun.net. FTP. ftploginexception;
Public class TTT extends jframe implements actionlistener {
Ftpclient FTP = NULL;
Private list ftplist = new list ();
Private list nativelist = new list ();
Private jpanel ftpclientframe = new jpanel (New borderlayout ());
Private jpanel ftpclientframeone = new jpanel (New flowlayout (
Flowlayout. Left ));
Private jpanel ftpclientframetwo = new jpanel (New gridlayout (1, 8 ));
Private jpanel ftpclientframethree = new jpanel (New gridlayout (2, 1 ));
Private jpanel ftpclientframefour = new jpanel (New gridlayout (1, 2 ));
// Connection and disconnection buttons
Private jbutton linkbutton = new jbutton ("Link ");
Private jbutton breakbutton = new jbutton ("break ");
Private jbutton uploadbutton = new jbutton ("Upload ");
Private jbutton downloadbutton = new jbutton ("Download ");
// Connection status
Private jlabel statuslabel = new jlabel ();
// User Logon
Private jlabel urllabel = new jlabel ("ftp url :");
Private jlabel usernamelabel = new jlabel ("username :");
Private jlabel passwordlabel = new jlabel ("Password :");
Private jlabel portlabel = new jlabel ("port :");
Private jtextfield urltextfield = new jtextfield ("10.10.103.21", 10 );
Private jtextfield usernametextfield = new jtextfield ("gridmiddleware", 10 );
Private jtextfield passwordtextfield = new jtextfield ("Three @ project", 10 );
Private jtextfield porttextfield = new jtextfield ("6000", 10 );
// Local and remote Windows
Defaultlistmodel modellist = new defaultlistmodel ();
Public TTT (){
Ftpclientframeone. Add (linkbutton );
Ftpclientframeone. Add (breakbutton );
Ftpclientframeone. Add (uploadbutton );
Ftpclientframeone. Add (downloadbutton );
Ftpclientframeone. Add (statuslabel );
Ftpclientframetwo. Add (urllabel );
Ftpclientframetwo. Add (urltextfield );
Ftpclientframetwo. Add (usernamelabel );
Ftpclientframetwo. Add (usernametextfield );
Ftpclientframetwo. Add (passwordlabel );
Ftpclientframetwo. Add (passwordtextfield );
Ftpclientframetwo. Add (portlabel );
Ftpclientframetwo. Add (porttextfield );
Ftpclientframethree. Add (ftpclientframeone );
Ftpclientframethree. Add (ftpclientframetwo );
Ftpclientframefour. Add (nativelist );
Ftpclientframefour. Add (ftplist );
Ftpclientframe. Add (ftpclientframethree, "North ");
Ftpclientframe. Add (ftpclientframefour, "center ");
Setcontentpane (ftpclientframe );
Settitle ("FTP client ");
Setsize (600,500 );
Setdefaclocloseoperation (jframe. exit_on_close );
Setvisible (true );
Linkbutton. addactionlistener (this );
Breakbutton. addactionlistener (this );
Uploadbutton. addactionlistener (this );
Downloadbutton. addactionlistener (this );
}
Public String getdir (string path ){
String dirname;
// Int ch;
Int begin = 55;
Dirname = path. substring (BEGIN). Trim ();
Return dirname;
}
Public void loadftplist (){
Stringbuffer Buf = new stringbuffer ();
Int ch;
Ftplist. removeall ();
Try {
Telnetinputstream T = ftp. List ();
T. setstickycrlf (true );
While (CH = T. Read ()> = 0 ){
If (CH = '/N '){
Ftplist. Add (getdir (BUF. tostring ()));
Buf. setlength (0 );
} Else {
Buf. append (char) CH );
}
}
} Catch (ioexception e ){
E. printstacktrace ();
}
Ftplist. Validate ();
}
Public void actionreceivmed (actionevent EVT ){
Object source = EVT. getsource ();
If (Source = linkbutton ){
// Connect to the FTP server
Try {
If (FTP! = NULL)
FTP. closeserver ();
Statuslabel. settext ("connection in progress, please wait .....");
FTP = new ftpclient (urltextfield. gettext (), integer
. Parseint (porttextfield. gettext ()));
FTP. login (usernametextfield. gettext (), passwordtextfield
. Gettext ());
FTP. Binary ();
} Catch (ftploginexception e ){
Joptionpane. showmessagedialog (null, "login failure !!! ");
E. printstacktrace ();
} Catch (ioexception e ){
Joptionpane. showmessagedialog (null, urltextfield. gettext ()
+ "Connection failure !!! ");
E. printstacktrace ();
} Catch (securityexception e ){
Joptionpane. showmessagedialog (null, "No purview !!! ");
E. printstacktrace ();
}
If (urltextfield. gettext (). Equals (""))
Joptionpane. showmessagedialog (null, "the FTP server address cannot be blank !!! ");
Else if (usernametextfield. gettext (). Equals (""))
Joptionpane. showmessagedialog (null, "the user name cannot be blank !!! ");
Else if (passwordtextfield. gettext (). Equals (""))
Joptionpane. showmessagedialog (null, "the password cannot be blank !!! ");
Else
Statuslabel. settext ("connected to FTP:" + urltextfield. gettext ());
Loadftplist ();
}
If (Source = uploadbutton ){
// String rwfiledir = "F: // gridmiddleware ";
Telnetoutputstream outs;
String message = "";
String filepathname = "E: // 1234.txt ";
If (FTP! = NULL ){
Statuslabel. settext ("uploading files ");
Try {
FTP. Cd (ftp. pwd () + "// SRC ");
String fg = new string ("E ://");
Int Index = filepathname. lastindexof (FG );
String filename = filepathname. substring (index + 1 );
Randomaccessfile sendfile = new randomaccessfile (
Filepathname, "R ");
Sendfile. Seek (0 );
Outs = ftp. Put (filename );
Dataoutputstream outputs = new dataoutputstream (outs );
Int ch;
While (sendfile. getfilepointer () <sendfile. Length ()){
Ch = sendfile. Read ();
Outputs. Write (CH );
}
Outs. Close ();
Sendfile. Close ();
Message = "uploaded" + filepathname + "file succeeded! ";
System. Out. println (Message );
} Catch (ioexception e ){
Message = "Upload Failed ";
// System. Out. println ("Upload" + filepathname + "file to" + rwfiledir
// + "Directory failed! "+ E );
System. Out. println (Message );
}
Statuslabel. settext (Message );
}
}
// Download the code
If (Source = downloadbutton ){
String filepathname = ftplist. getselecteditem ();
If (filepathname = NULL)
Joptionpane. showmessagedialog (null, "select the file to download !!! ");
String baddir = "E: // download_test //";
String message = "";
If (FTP! = NULL ){
Statuslabel. settext ("downloading ...");
Try {
Int ch;
File Fi = new file (baddir + filepathname );
Randomaccessfile GetFile = new randomaccessfile (FI, "RW ");
GetFile. Seek (0 );
Telnetinputstream fget = ftp. Get (filepathname );
Datainputstream puts = new datainputstream (fget );
While (CH = puts. Read ()> = 0 ){
GetFile. Write (CH );
}
Fget. Close ();
GetFile. Close ();
Message = "Download successful! ";
System. Out. println ("Download" + filepathname + "file to" + baddir
+ "Directory succeeded! ");
} Catch (ioexception e ){
Message = "Download failed! ";
System. Out. println ("Download" + filepathname + "file to" + baddir
+ "Directory failed! "+ E );
}
}
Statuslabel. settext (Message );
}
// Todo: The above code is added.
If (Source = breakbutton ){
System. Exit (0 );
}
}
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
TTT ftpclientframe = new TTT ();
}
}
Ii. Example of using org.apache.commons.net. FTP. ftpclient:
Package org. gridsphere. g2rpbrt. portlets;
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 java.net. socketexception;
Import org.apache.commons.net. FTP. FTP;
Import org.apache.commons.net. FTP. ftpclient;
Import org.apache.commons.net. FTP. ftpfile;
Public class ftputil {
Ftpclient;
// Connect to the FTP server
Public void connectserver (string server, int port, string user,
String password, string path) throws socketexception, ioexception {
Ftpclient = new ftpclient ();
Ftpclient. Connect (server, Port );
System. Out. println ("connected to" + SERVER + ".");
System. Out. println (ftpclient. getreplycode ());
Ftpclient. login (user, password );
// Path is the sub-path of the FTP path
If (path. Length ()! = 0 ){
Ftpclient. changeworkingdirectory (PATH );
}
}
/**
* Close the connection.
**/
Public Boolean closeconnect (){
Boolean flag = false;
Try {
Ftpclient. Disconnect ();
System. Out. println ("Disconnect success !!! ");
} Catch (ioexception e ){
System. Out. println ("not disconnect !!! ");
System. Out. println (E. getmessage ());
Flag = false;
Return flag;
}
Return flag;
}
// FTP upload
Public Boolean uploadfile (string filename)
Throws ioexception {
Boolean flag = false;
String remotename;
Ftpclient. makedirectory ("pbrt ");
Ftpclient. changeworkingdirectory ("pbrt ");
Inputstream istream = NULL;
Try {
Istream = new fileinputstream (filename );
Remotename = filename. substring (filename. lastindexof ("//") + 1 );
Flag = ftpclient. storefile (remotename, istream );
} Catch (ioexception e ){
Flag = false;
Return flag;
} Finally {
If (istream! = NULL ){
Istream. Close ();
}
}
Return flag;
}
// Convert the Chinese directory name
Public static string encode (string Str ){
Try {
String encodestr = new string (Str. getbytes ("gb2312"), "iso-8859-1 ");
Return encodestr;
} Catch (exception ex ){
Ex. printstacktrace ();
Return NULL;
}
}
// FTP download, which downloads all files in a folder
Public Boolean download (string localpath) throws ioexception {
Boolean flag = false;
Ftpclient. changeworkingdirectory ("TIF ");
String dfn = "";
Outputstream ostream = NULL;
String [] LFN = ftpclient. listnames ();
Try {
For (INT I = 0; I <LFN. length; I ++ ){
Dfn = localpath + LFN [I];
File OUTFILE = new file (dfn );
Ostream = new fileoutputstream (OUTFILE );
Flag = ftpclient. retrievefile (LFN [I], ostream );
}
For (Int J = 0; j <LFN. length; j ++ ){
Ftpclient. deletefile (LFN [J]);
}
Ftpclient. changeworkingdirectory ("//");
Ftpclient. removedirectory ("TIF ");
Ftpclient. changeworkingdirectory ("pbrt ");
String [] PFN = ftpclient. listnames ();
For (int K = 0; k <PFN. length; k ++ ){
Ftpclient. deletefile (PFN [k]);
}
Ftpclient. changeworkingdirectory ("//");
Ftpclient. removedirectory ("pbrt ");
}
Catch (exception e ){
Flag = false;
Return flag;
} Finally {
Ostream. Close ();
}
Return flag;
}
Public static void main (string ARGs []) throws socketexception, ioexception {
Ftputil FFC = new ftputil ();
FFC. connectserver ("10.10.103.21", 6000, "Grid ",
"Grid903", "E: // film ");
// FFC. uploadfile ("D: // temp // CGSP-VEGA.exe ");
If (FFC. Download ("D: // TIF //")){
System. Out. println ("Download success ");
};
// System. Out. println (FFC. removedirectory ("001 "));
FFC. closeconnect ();
}
}