赞
踩
private String ip = "XXXXXXXX";
private String passWord = "XXXXXXXX";
private String username = "XXXXXXXX";
private int port = XXXXXXXX;
private static String dir = "XXXXXXXX";//文件所在目录以及保存目录,这里用了一个
private String fileName = "XXXXXXXX";
private String fileType = ".xls";
//总入口
public void download() {
FTPClient client = getclient();
createLocalFilesFromFtp(client);
}
//获得FTPClient:
public FTPClient getclient() {
Logger.info("连接ftp");
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ip, port);
ftpClient.login(username, passWord);// 登录
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) { // 是否连接成功
ftpClient.disconnect(); // 断开连接
}
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
} catch (Exception e) {
Logger.info("连接失败,失败原因:" + e.getMessage() + "!");
e.printStackTrace();
}
return ftpClient;
}
//保存文件到本地
public void createLocalFilesFromFtp(FTPClient ftpClient) {
Map<Object, Object> map = new HashMap<Object, Object>();
try {
ftpClient.changeWorkingDirectory(dir);
FTPFile[] fs = ftpClient.listFiles();
//判断本地存放文件的目录是否已存在,不存在新建目录
File vfile = new File("xx");
if (!vfile.exists()) {
vfile.mkdirs();
}
int fileLength = fs.length;
if (fileLength > 0) {
for (FTPFile file : fs) {
Date date = new Date();
if (XString.equals(file.getName(), getfilename())) {
Logger.info("将要下载的文件名:" + getfilename());
OutputStream is = new FileOutputStream("xx/"
+ getfilename());
Boolean issuccess = ftpClient.retrieveFile(
getfilename(), is);
is.close();
}
}
} else {
map.put("success", false);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。