We may need to use FTP in the project to upload files, download, get server directory information and other related operations, we can use Apache ftpclient to carry out related operations, the following public methods related to share with you, each method before the detailed comments to explain, However, in the FTP test, we need to configure an FTP server, file upload and download, we can find relevant information on the Internet to set up, the environment can be built to carry out our test, we do apche FTP related operations, we need a jar package support, Commons-net.jar, you can download it in my library for free:
http://download.csdn.net/detail/harderxin/7053691
Write our Ftpcongfig class to encapsulate the login information as our entity class:
Package com.xin.test;
/**
* FTP Login configuration information
* @author harderxin
* * *
/Public
class Ftpconfig {
//server address name
private String server;
Port number
private int port;
User name
private String username;
Password
private String password;
Working directory
private String location;
Public String Getserver () {
return server;
}
public void Setserver (String server) {
this.server = server;
}
public int Getport () {
return port;
}
public void Setport (int port) {
this.port = port;
}
Public String GetUserName () {
return username;
}
public void Setusername (String username) {
this.username = username;
}
Public String GetPassword () {
return password;
}
public void SetPassword (String password) {
this.password = password;
}
Public String getLocation () {
return location;
}
public void setlocation (String location) {
this.location = location;
}
}
2, write our ftputil for FTP-related operations:
Package com.xin.test;
Import Java.io.BufferedInputStream;
Import Java.io.BufferedOutputStream;
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 java.util.ArrayList;
Import java.util.List;
Import Org.apache.commons.net.ftp.FTP;
Import org.apache.commons.net.ftp.FTPClient;
Import Org.apache.commons.net.ftp.FTPFile;
Import Org.apache.commons.net.ftp.FTPFileFilter;
public class Ftputil {private FtpClient ftpclient;
public static final int binary_file_type = Ftp.binary_file_type;
public static final int ascii_file_type = Ftp.ascii_file_type;
/** * Server connection with Ftpconfig * @param ftpconfig parameter Configuration Bean class * @throws socketexception * @throws IOException */public void ConnectServer (Ftpconfig ftpconfig) throws SocketException, IOException {S Tring Server = Ftpconfig.getserver ();
int port = Ftpconfig.getport ();
String user = Ftpconfig.getusername ();
String password = Ftpconfig.getpassword ();
String location = Ftpconfig.getlocation ();
ConnectServer (server, port, user, password, location); /** * Use details for server connection * @param server: Server address name * @param port: Port number * @param User: Username *
@param Password: User password * @param path: Transfer to FTP server directory * @throws socketexception * @throws IOException */ public void ConnectServer (string server, int port, string user, string password, string path) throws Socket
Exception, IOException {ftpclient = new ftpclient ();
Ftpclient.connect (server, port);
System.out.println ("Connected to" + Server + ".");
The response code after successful connection System.out.println (Ftpclient.getreplycode ());
Ftpclient.login (user, password); if (Path!=null&&path.length ()! = 0){ftpclient.changeworkingdirectory (path); } ftpclient.setbuffersize (1024);//Set Upload cache size ftpclient.setcontrolencoding ("UTF-8");//Set Encoding Ftpclient.setfile Type (binary_file_type);//Set File type}/** * Set transfer file type: FTP. Binary_file_type | Ftp. Ascii_file_type * binary file or text file * @param fileType * @throws IOException */public void Setfiletype (
int FileType) throws IOException {Ftpclient.setfiletype (fileType);
/** * Close Connection * @throws IOException */public void CloseServer () throws IOException { if (ftpclient!=null&&ftpclient.isconnected ()) {ftpclient.logout ();//exit FTP server FTPCLIENT.D Isconnect ();//Close FTP connection}}/** * Transfer to FTP server working directory * @param path * @return * @throw S IOException */public boolean changedirectory (String path) throws IOException {return Ftpclient.chan Geworkingdirectory (Path); /** * Create directory on server * @param pathName * @return * @throws IOException */public bool
Ean CreateDirectory (String pathName) throws IOException {return ftpclient.makedirectory (pathName); /** * Delete directory on server * @param path * @return * @throws IOException */Public Boolean
RemoveDirectory (String path) throws IOException {return ftpclient.removedirectory (path); }/** * Delete all files and directories * @param path * @param isall true: Delete all files and directories * @return * @throws IO
Exception */Public boolean removedirectory (String path, Boolean Isall) throws IOException {
if (!isall) {return removedirectory (path);
} ftpfile[] Ftpfilearr = ftpclient.listfiles (path);
if (Ftpfilearr = = NULL | | ftpfilearr.length = = 0) {return removedirectory (path); }
//
for (Ftpfile Ftpfile:ftpfilearr) {String name = Ftpfile.getname ();
if (Ftpfile.isdirectory ()) {System.out.println ("* [Sd]delete subpath [" +path + "/" + name+ "]");
RemoveDirectory (path + "/" + name, true);
} else if (Ftpfile.isfile ()) {System.out.println ("* [Sf]delete file [" +path + "/" + name+ "]");
DeleteFile (path + "/" + name);
} else if (Ftpfile.issymboliclink ()) {} else if (Ftpfile.isunknown ()) {}}
return ftpclient.removedirectory (path);
}/** * Checks if the directory exists on the server true: false exists: * @param path * @return * @throws IOException
*/Public Boolean existdirectory (String path) throws IOException {Boolean flag = false;
ftpfile[] Ftpfilearr = ftpclient.listfiles (path); For (Ftpfile Ftpfile: Ftpfilearr) {if (Ftpfile.isdirectory () && ftpfile.getname (). equalsignorecase (path))
{flag = true;
Break
}} return flag; /** * Get a list of files, Listfiles returns the containing directory and file, it returns a ftpfile array * listnames (): An array of strings containing only directories * string[] Filenamear
r = ftpclient.listnames (path);
* @param path: File directory on server:/DF4 */Public list<string> getfilelist (String path) throws IOException {
Ftpfile[] ftpfiles= ftpclient.listfiles (path); Through Ftpfilefilter traversal only get File/* ftpfile[] ftpfiles2= ftpclient.listfiles (path,new ftpfilefilter () {@Override publi
C Boolean Accept (Ftpfile ftpfile) {return ftpfile.isfile (); }
});
*/list<string> Retlist = new arraylist<string> ();
if (Ftpfiles = = NULL | | ftpfiles.length = = 0) {return retlist; } for (Ftpfile ftpfile:ftpfiles) {
if (Ftpfile.isfile ()) {Retlist.add (Ftpfile.getname ());
}} return retlist; /** * Delete files on server * @param pathName * @return * @throws IOException */Public Boolea
N DeleteFile (String pathName) throws IOException {return ftpclient.deletefile (pathName);
/** * Upload files to FTP server * When uploading and downloading files, it is best to set the file type: * Ftputil.setfiletype (Ftputil.binary_file_type) * Localfilepath: Local file path and name * remotefilename: Server file name */public boolean uploadfile (String Localfilepath, Str
ing Remotefilename) throws IOException {Boolean flag = false;
InputStream iStream = null;
try {iStream = new FileInputStream (Localfilepath);
We can use Bufferedinputstream for encapsulation//bufferedinputstream bis=new Bufferedinputstream (IStream); Flag = Ftpclient.storefile (remotefilename, bis);
Flag = Ftpclient.storefile (Remotefilename, IStream);
} catch (IOException e) {flag = false;
return flag;
} finally {if (IStream! = null) {istream.close ();
}} return flag;
/** * Upload file to FTP server, upload new file name as the original name * @param fileName: File name * @return * @throws IOException
*/Public Boolean uploadfile (String filename) throws IOException {return uploadfile (filename, filename); /** * Upload file to FTP server * @param iStream input stream * @param newName new file name * @return * @throw S IOException */public boolean uploadfile (InputStream iStream, String newName) throws IOException
{Boolean flag = false;
try {flag = Ftpclient.storefile (NewName, IStream);
} catch (IOException e) {flag = false;
return flag; } finally {if (IStream! = null) {istream.close ();
}} return flag; /** * Download files from FTP server to local * @param remotefilename:ftp file name on server * @param localfilename: Local file name * @
return * @throws IOException */public boolean download (string remotefilename, String localfilename)
Throws IOException {Boolean flag = false;
File outfile = new file (LocalFilename);
OutputStream oStream = null;
try {oStream = new FileOutputStream (outfile);
We can use Bufferedoutputstream for encapsulation//bufferedoutputstream bos=new Bufferedoutputstream (OStream);
Flag = Ftpclient.retrievefile (remotefilename, BOS);
Flag = Ftpclient.retrievefile (Remotefilename, OStream);
} catch (IOException e) {flag = false;
return flag; } finally {OStream.Close ();
} return flag; /** * Download files from FTP server to local * @param sourcefilename: Server resource file name * @return InputStream input stream * @th Rows IOException */public InputStream downfile (String sourcefilename) throws IOException {return FTPC
Lient.retrievefilestream (sourceFileName); }
}
3. Write our test class:
public static void Main (String args[]) throws exception{
//testupload ();
Testdownload ();
Ftputil ftputil=new ftputil ();
Ftputil.connectserver ("192.168.1.254", Ftpclient.default_port, "image", "123456", null);
Obtain all file names under directory name DF4 on the FTP server
list<string> list=ftputil.getfilelist ("/df4");
System.out.println ("File name list is:" +list);
Upload the local D disk file Aaa.txt to the server, the server name is called Bbb.txt
ftputil.uploadfile ("D:" + File.separator + "Aaa.txt", "Eee.txt");
Download the file from the server bbb.txt to the local D-disk name Ccc.txt
ftputil.download ("Eee.txt", "D:" + File.separator + "Fff.txt");
Delete files on FTP server: Bbb.txt
//ftputil.deletefile ("Bbb.txt");
}
There are similar requirements, we can use the above code for reference, for Exchange learning!!