Java FTP upload a file directory example

Source: Internet
Author: User

Java FTP upload a file directory

Package yq1012;
Import Java.io.File;
Import Java.io.FileInputStream;
Import org.apache.commons.net.ftp.FTPClient;
Import org.apache.commons.net.ftp.FTPReply;

public class Test {

Private ftpclient FTP;
/**
*
* @param path uploaded to the FTP server
* @param addr Address
* @param Port Port number
* @param username User name
* @param password Password
* @return
* @throws Exception
*/
Private Boolean connect (String path,string addr,int port,string username,string password) throws Exception {
Boolean result = false;
FTP = new FtpClient ();
int reply;
Ftp.connect (Addr,port);
Ftp.login (Username,password);
Ftp.setfiletype (Ftpclient.binary_file_type);
Reply = Ftp.getreplycode ();
if (! Ftpreply.ispositivecompletion (Reply)) {
Ftp.disconnect ();
return result;
}
Ftp.changeworkingdirectory (path);
result = true;
return result;
}
/**
*
* @param files or folders uploaded by file
* @throws Exception
*/
private void upload (file file) throws exception{
if (File.isdirectory ()) {
Ftp.makedirectory (File.getname ());
Ftp.changeworkingdirectory (File.getname ());
string[] files = file.list ();
for (int i = 0; i < files.length; i++) {
File File1 = new file (File.getpath () + "\" +files[i]);
if (File1.isdirectory ()) {
Upload (file1);
Ftp.changetoparentdirectory ();
}else{
File File2 = new file (File.getpath () + "\" +files[i]);
FileInputStream input = new FileInputStream (file2);
Ftp.storefile (File2.getname (), input);
Input.close ();
}
}
}else{
File File2 = new file (File.getpath ());
FileInputStream input = new FileInputStream (file2);
Ftp.storefile (File2.getname (), input);
Input.close ();
}
}
public static void Main (string[] args) throws exception{
String url = "Www.111cn.net";
String username = "user";
String password = "password";

Test T = new Test ();
T.connect ("", url, username, password);
File File = new file ("D:\\xinxi");
T.upload (file);
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.