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);
}
}