Case:
三台主机,A、B、C;A,winXP;B、Win 2003;C、Linux
A只能远程连接到B,通过B连接C;
每天需要在服务器C上下载数据,现在用java在B上搭建一个FTP服务器,说白了也就是用java语言写一个FTP客户端,实现对远端数据的下载。在B上通过ETL工具将数据下载到A上。
代码如下:
package com.mcm.socket.ftp;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class AA{
public static FTPClient ftpClient =new FTPClient();
public static String encoding =System.getProperty("file.encoding");
public static boolean download(String url,int port,String username,
String password,String localPath,String remotePath){
boolean result =false;
int reply;
try{
ftpClient.setControlEncoding(encoding);//
ftpClient.connect(url,port);//建立连接
ftpClient.login(username, password);//登录
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//编码格式
reply = ftpClient.getReplyCode();//答应码
//验证是否登录成功
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.err.println("FTP server refused connection.");
}
}catch(Exception e){
e.printStackTrace();
}
FileOutputStream outStream = null;
FTPFile[] list = null;
try{
list = ftpClient.listFiles(remotePath);
File temp = null;
for (int i = 0; i < list.length; i++) {
// 如果是文件,则直接执行下载
if (list[i].isFile()) {
ftpClient.changeWorkingDirectory(remotePath);
String fileName = list[i].getName();
temp = new File(localPath + File.separator + fileName);
outStream = new FileOutputStream(temp);
boolean isDownload = ftpClient.retrieveFile(fileName, outStream);//判断是目录还是文件
outStream.close();
if(isDownload==true){}
}
else if (list[i].isDirectory())// 是目录
{
temp = new File(localPath + File.separator + list[i].getName());
temp.mkdirs();
//String newRemote = remotePath + File.separator + list[i].getName();
}
}
}catch(Exception e){
e.printStackTrace();
}finally {
try{
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
return result;
}
//关闭连接
public void closeFtpConn(){
try{
if(ftpClient.isConnected()||ftpClient != null){
ftpClient.disconnect();
}
ftpClient = null;
}catch(Exception e){
e.printStackTrace();
}
}
//下载
public void downloadFiles(){
try{
FTPClientConfig config=new FTPClientConfig(FTPClientConfig.SYST_UNIX);
ftpClient.configure(config);
download("目的主机IP",21,"用户名","密码","F:/temp/jituanhecha/","/20130124");
//目的主机就是远端服务器的IP,用户名密码就是登陆FTP的账号密码,本地目录,远端目录(这有个问题:怎么把远端目录设置成动态的,因为远端目录他是按时间生成的文件名???)
}catch(Exception e){
e.printStackTrace();
}
}
//主函数
public static void main(String[] args){
AA ftpdown=new AA();
ftpdown.downloadFiles();
}
}