Required jar package: commons-io-1.3.2.jar commons-net-3.0.1.jar
First, create an FTP server on your computer. There are many software available on the Internet. I use Quick easy FTP server.
Here the root directory of the server is: e:/myftp
Package FTP;
Import org. Apache. commons. Io. ioutils;
Import org.apache.commons.net. FTP. ftpclient;
Import java. Io. file;
Import java. Io. fileinputstream;
Import java. Io. ioexception;
Import java. Io. fileoutputstream;
Public class ftptest
{
Public static void main (string [] ARGs)
{
Testupload ();
Testdownload ();
}
/**
* Upload a single file over FTP
*/
Public static void testupload ()
{
Ftpclient = new ftpclient ();
Fileinputstream fin = NULL;
Try
{
Ftpclient. setdefaultport (222 );
Ftpclient. Connect ("192.168.199.117 ");
If (! Ftpclient. login ("admin", "admin "))
{
System. Out. Print ("Login error! ");
Return;
}
// The file to be uploaded is touxiang.jpg
File srcfile = new file ("E:/myftp/touxiang.jpg ");
Fin = new fileinputstream (srcfile );
// Set the upload directory. Upload is the next level folder in the root directory.
Ftpclient. changeworkingdirectory ("/upload ");
Ftpclient. setbuffersize (1024 );
Ftpclient. setcontrolencoding ("GBK ");
// Set the file type (Binary)
Ftpclient. setfiletype (ftpclient. binary_file_type );
// The uploaded file is stored as an upload.jpg file.
Ftpclient. storefile ("upload.jpg", fin );
}
Catch (ioexception E)
{
E. printstacktrace ();
Throw new runtimeexception ("Some FTP client error happened! ", E );
}
Finally
{
Ioutils. closequietly (FIN );
Try
{
Ftpclient. Disconnect ();
}
Catch (ioexception E)
{
E. printstacktrace ();
Throw new runtimeexception ("failed to close FTP connection! ", E );
}
}
}
/**
* FTP download single file test
*/
Public static void testdownload ()
{
Ftpclient = new ftpclient ();
Fileoutputstream Fos = NULL;
Try
{
Ftpclient. setdefaultport (222 );
Ftpclient. Connect ("192.168.199.117 ");
If (! Ftpclient. login ("admin", "admin "))
{
System. Out. Print ("Login error! ");
Return;
}
String remotefilename = "/touxiang.jpg ";
Fos = new fileoutputstream ("E: myftp/download/down.jpg ");
Ftpclient. setbuffersize (1024 );
// Set the file type (Binary)
Ftpclient. setfiletype (ftpclient. binary_file_type );
Ftpclient. retrievefile (remotefilename, FOS );
}
Catch (ioexception E)
{
E. printstacktrace ();
Throw new runtimeexception ("Some FTP client error happened! ", E );
}
Finally
{
Ioutils. closequietly (FOS );
Try
{
Ftpclient. Disconnect ();
}
Catch (ioexception E)
{
E. printstacktrace ();
Throw new runtimeexception ("failed to close FTP connection! ", E );
}
}
}
}