import java.io.IOException;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPException;
import com.enterprisedt.net.ftp.FTPTransferType;
public class TestFTPDownload {
private String hostName = "198.98.251.94";//FTP IP
private String userName = "root";//连接FTP的账号
private String password = "root";//连接FTP的密码
private int remotePort = 21;//端口号,默认为21
private String localDirName = "I:/data/20160320/";//本地文件夹
private String remoteDirName = "/data/20160320";//FTP中的文件夹
/**
* 建立FTP连接
* @throws FTPException
* @throws IOException
*/
public FTPClient connectFTP() throws IOException, FTPException{
FTPClient client = new FTPClient();
client.setRemoteHost(hostName);
client.setRemotePort(remotePort);
client.setControlEncoding("GB2312");
client.connect();
client.setTimeout(12000);//设置超时时间
client.login(userName, password);
client.setType(FTPTransferType.BINARY);//二进制
client.setConnectMode(FTPConnectMode.PASV);//以波动模式链接
return client;
}
/**
* 改变远程虚拟目录路径
* @param client
* @return
*/
public boolean changeRemoteDir(FTPClient client){
String[] dirName = remoteDirName.split("/");
for(int i=0;i<dirName.length;i++){
try {
//逐层进入文件夹
System.out.println(dirName[i]);
client.chdir(dirName[i]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (FTPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
return true;
}
/**
* 下载文件
* @param client
* @return
*/
public boolean downloadFile(FTPClient client){
try {
String[] files = client.dir();
for(int i=0;i<files.length;i++){
client.get(localDirName+files[i],files[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (FTPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestFTPDownload test = new TestFTPDownload();
try {
FTPClient client = test.connectFTP();
if(test.changeRemoteDir(client)){
test.downloadFile(client);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FTPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}