package com.company.project.utils;
import java.io.*;
import java.util.zip.GZIPInputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* 描述信息:FTP下载
*
* @author xieyuchun
* @version 1.0
* <p>
* <p>
* <p>
* 完成日期:2014-06-19
*/
public class FtpClientDownfile {
private static final String url = "10.*.*.4";
private static final int port = 21;
private static final String username = "ftpuser";
private static final String password = "123456";
private static final String remotePath = "/data/ftp/"; //FTP服务器上的绝对路径
private static final String localPath = "E:\\data\\"; //下载后保存到本地的路径
public static void main(String[] args) {
downFile(url, port, username, password, remotePath, localPath);
}
/**
* Description: 从FTP服务器下载文件
*
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath FTP服务器上的相对路径
* @param localPath 下载后保存到本地的路径
* @return
* @Version1.0
*/
public static boolean downFile(String url, int port, String username, String password, String remotePath, String localPath) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
ftp.enterLocalPassiveMode(); //开启被动模式,跟端口是否开放有关,更多详情请百度
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
System.out.println("=========" + ff.getName());
File localFile = new File(localPath + "/" + ff.getName());
if (!localFile.exists()) {
System.out.println("本地目录文件不存在,正在写入。。。");
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
} else {
System.out.println("本地目录文件已存在,暂停写入,跳转下一个文件!");
}
//下载完成后解压
unGzipFile(localPath+ff.getName());
}
ftp.logout();
System.out.println("文件下载完成!");
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
return success;
}
/**
* 解压文件
* @param sourcedir 文件目录及文件名字
*/
public static void unGzipFile(String sourcedir) {
String ouputfile = "";
try {
//建立gzip压缩文件输入流
FileInputStream fin = new FileInputStream(sourcedir);
//建立gzip解压工作流
GZIPInputStream gzin = new GZIPInputStream(fin);
//建立解压文件输出流
ouputfile = sourcedir.substring(0,sourcedir.lastIndexOf('.'));
// ouputfile = ouputfile.substring(0,ouputfile.lastIndexOf('.'));
FileOutputStream fout = new FileOutputStream(ouputfile);
int num;
byte[] buf=new byte[1024];
while ((num = gzin.read(buf,0,buf.length)) != -1)
{
fout.write(buf,0,num);
}
gzin.close();
fout.close();
fin.close();
} catch (Exception ex){
System.err.println(ex.toString());
}
return;
}
}
加了一步 :
ftp.enterLocalPassiveMode(); //开启被动模式,跟端口是否开放有关,更多详情请百度