Import Packages First
Import org.apache.commons.net.ftp.FTPClient;
Import Org.apache.commons.net.ftp.FTPFile;
The FtpClient class library mainly provides classes for establishing an FTP connection. Using these classes, programmers can log on remotely to an FTP server, enumerate directories on the server, set up transport protocols, and transfer files. The FtpClient class covers almost all FTP functionality, and ftpclient instance variables hold various information about establishing a "broker." These instance variables are given below.
public static Boolean Useftpproxy
This variable is used to indicate whether an agent was used during FTP transfer, so it is actually a tag, which, if true, indicates the use of a proxy host.
public static String Ftpproxyhost
This variable is valid only if the variable useftpproxy is true, and is used to save the proxy host name.
public static int Ftpproxyport
This variable is valid only if the variable useftpproxy is true, and is used to save the port address of the proxy host.
FtpClient has three different types of constructors, as follows:
1. Public ftpclient (String hostname,int Port)
This constructor uses the given host name and port number to establish an FTP connection.
2. Public ftpclient (String hostname)
This constructor creates an FTP connection with the given host name, using the default port number.
3, FtpClient ()
This constructor creates a FtpClient class, but does not establish an FTP connection. At this point, the FTP connection can be established using the OpenServer method.
Once the class ftpclient is established, you can use this class method to open the connection to the FTP server. Class FtpClient provides the following two methods that you can use to open a connection to an FTP server.
public void OpenServer (String hostname)
This method is used to establish a connection to the FTP server on the specified host, using the default port number.
public void OpenServer (String host,int Port)
This method is used to establish a connection to the FTP server on the specified host, specified port.
After you open the connection, the next step is to register to the FTP server. The following methods need to be used.
public void Login (String username,string password)
This method logs on to the FTP server using parameter username and password. Users who have used Intemet should know that the anonymous FTP server's login username is anonymous and the password is generally in its own e-mail address.
The following are some of the control commands provided by the FtpClient class.
public void CD (String remotedirectory)
This command switches the directory on the remote system to the directory specified by the parameter remotedirectory.
public void Cdup (): This command is used to switch directories on the remote system to the previous directory.
Public String pwd (): This command displays the status of the directory on the remote system.
public void Binary (): This command sets the transport format to binary format.
public void ASCII (): This command sets the transport protocol to an ASCII format.
public void rename (String string,string string1)
This command renames a directory or file on a remote system.
In addition to the above methods, class FtpClient also provides several methods that can be used to pass and retrieve catalog listings and files. These methods return input and output streams that are available for reading or writing. Here are some of the main methods.
Public Telnetinputstream list ()
Returns the input stream corresponding to the current directory on the remote machine.
Public Telnetinputstream get (String filename)
Gets the file filename on the remote machine, using Telnetinputstream to transfer the file to the local.
Public Telnetoutputstream put (String filename)
Opens an output stream by writing to transmit file filename to the remote computer through this output stream.
Case:
Public ftpclient FTP = new FtpClient (); Instantiates the FTP client object.
/******************* Landing ***********************/
Start reading to connect to FTP server
if (ftp.isconnected () = = False)
{
Try
{
Ftp.connect (HOST_IP)//Connection FTP host_ip FTP server IP
Try
{
Ftp.login (username, password)/login login () method login FTP
Ftp.setfiletype (Ftpclient.ascii_file_type)//Set File type Setfiletype () set FTP file type
catch (Exception E1)
{
Log.error ("Faile to load!!!!");
}
catch (SocketException E1)
{
Log.error ("Establish connection FTP connection failed");
catch (IOException E1)
{
Log.error ("IO exception FTP.txt read failed");
}
}
/************** Download File ***************************/
public void Downloadfiles ()
{
Access to the FTP server working directory
Ftp.changeworkingdirectory (ftp.printworkingdirectory () + Remote_dir); Remote_dir FTP Remote file directory
Get a list of files in a remote FTP directory
ftpfile[] filelist = Ftp.listfiles ("."); // . Can be used to specify an FTP directory for files. Gets a list of ftpfile files. Note: The file list contains folders and files
string[] files = ftp.listnames (); Gets the list of FTP server file names. Note: The file list contains the names of folders and files.
/*
Filelist[0].getgroup (); File belongs to group, corresponding to set
Filelist[0].getname (); File name, SetName ("") renaming
Filelist[0].getsize (); File size Returns a Long data type
Filelist[0].gettimestamp (). GetTime (); File Last Modified Time
Filelist[0].gettype (); File type
Filelist[0].getuser (); User to which the file belongs
Filelist[0].isdirectory (); File is not a folder
Filelist[0].isfile (); Judge is not a file
Filelist[0].issymboliclink (); 。。。
Filelist[0].isunknown (); 。 、、
Filelist[0]. Directory_type; property, the folder type returns the int type
Filelist[0]. File_type; property, file type, return int type
Filelist[0]. group_access; Group, returning INT type
*/
When downloading the specified file, determine the name of the specified file, such as download, AA. TXT file
Traversal gets the list of FTP file names
for (int i; i < filelist.length (callout: or files.length); i + +)
{
Determines whether the filename contains AA.txt. Note: The FileList object cannot get the length attribute in Linux. Must be obtained through the Files property. The list of file names must also be retrieved from the files array.
if (Filelist[i].getname (). IndexOf ("AA.txt")!=-1)
{
File LocalFile = new file (local_dir+ "/" +filelist[i].getname ());
OutputStream Ops = FileOutputStream (LocalFile);
Ftp.retrievefile (Filelist[i].getname (), OPS); Downloads a file with the specified file name on FTP to the folder of the local specified output stream.
Ops.close ();
}
}
}
/****************** upload the specified file ***********************/
/**
* Description: Uploading files to FTP server
* @Version1.0 2008 4:31:09 PM by Tri Hongbao (cuihongbao@d-heaven.com) created
* @param URL FTP server hostname
* @param port FTP server ports
* @param username FTP login Account
* @param password FTP login password
* @param path FTP server save directory
* @param filename uploaded to the FTP server
* @param input stream
* @return Returns True successfully, otherwise returns false
*/
public static Boolean UploadFile (String url,int port,string Username, string password, string path, string filename, Input Stream input) {
Boolean success = false;
ftpclient ftp = new FtpClient ();
try {
int reply;
Ftp.connect (URL, port);//Connect FTP server
If you use the default port, you can connect to the FTP server directly using the Ftp.connect (URL) method
Ftp.login (username, password);/Login
Reply = Ftp.getreplycode ();
if (! Ftpreply.ispositivecompletion (Reply)) {
Ftp.disconnect ();
return success;
}
Ftp.changeworkingdirectory (path);
Ftp.storefile (filename, input);
Input.close ();
Ftp.logout ();
Success = true;
catch (IOException e) {
E.printstacktrace ();
finally {
if (ftp.isconnected ()) {
try {
Ftp.disconnect ();
catch (IOException IoE) {
}
}
}
return success;
}
@Test
public void Testuploadfromdisk () {
try {
FileInputStream in=new FileInputStream (New File ("D:/test.txt"));
Boolean flag = UploadFile ("127.0.0.1", "Test", "Test", "D:/ftp", "test.txt", in);
SYSTEM.OUT.PRINTLN (flag);
catch (FileNotFoundException e) {
E.printstacktrace ();
}
}
Case one:
Using Apache FTP client to implement FTP clients--supporting breakpoint continuation and Chinese files
Use the ORG.APACHE.COMMONS.NET.FTP package to implement a simple FTP client utility class. Mainly realize the function
1. Support Upload and download. Support Breakpoint Continuation Pass
2. Support progress Report
3. Support for the Chinese directory and the creation of Chinese files.
Enumerating Class Uploadstatus Code
[Java] View Plain Copy 1. public enum UploadStatus { 2. create_directory_fail, // Remote server corresponding directory creation failure 3. create_directory_ success, //Remote Server Pathbreaker directory success 4. upload_new_file_success, //upload new file Success 5. upload_new_file_failed, //failed to upload new file 6. File_Exits, //file already exists 7. Remote_Bigger_Local, //remote file is greater than local file 8. upload_from_break _success, //Breakpoint continued success 9. upload_from_break_failed, //Breakpoint Continuation Failure 10. delete_remote_faild; //Delete remote file failed 11. }
Enumerating Class Downloadstatus Code
[C-sharp] view plain copy