ftp服务器下载文件

import java.io.*;
import java.net.SocketException;

import org.apache.commons.net.ftp.*;
/**
 * ftp服务器下载文件
 *
 */
public class FtpDownloadFileUtil {

	private static String host = "";
	private static String user = "";
	private static String password = "";
	private static String directory = "/home/ftpuser/gsi-war";
	private static String saveFile = "D:/saveftp";

	/**
	 * 获取FTPCLIENT
	 */
	public static FTPClient getFtpClient() throws SocketException, IOException {
		FTPClient ftp = new FTPClient();
		// 连接FTP服务器
		ftp.connect(host);
		// 登陆FTP服务器
		ftp.login(user, password);
		// 验证FTP服务器是否登录成功
		int replyCode = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(replyCode)) {
			System.out.println("登录验证失败");
		}
		// 中文支持
		ftp.setControlEncoding("UTF-8");
		ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
		// ftp.enterLocalPassiveMode(); // 被动模式
		ftp.enterLocalActiveMode(); // 主动模式
		ftp.changeWorkingDirectory(directory);
		return ftp;
	}

	/**
	 * FTP下载文件
	 */
	public static String download() {
		OutputStream os = null;
		String result = "";
		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient = getFtpClient();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("FTP连接发生异常!", e);
		}
		try {
			// 切换FTP目录
			ftpClient.changeWorkingDirectory(directory);
			FTPFile[] ftpFiles = ftpClient.listFiles();
			// 遍历目录下所有文件
			for (FTPFile file : ftpFiles) {
				String fileName = file.getName();
				if (fileName.indexOf(".") == -1) {
					continue;
				}
				String fileTyle = fileName.substring(fileName.lastIndexOf("."), fileName.length());
				if (".jio".equals(fileTyle)) {
					File localFile = new File(saveFile + File.separator + fileName);
					os = new FileOutputStream(localFile);
					ftpClient.retrieveFile(fileName, os);
					// 删除jio文件
					ftpClient.deleteFile(fileName);
					os.close();
				}
			}
			System.out.println("ftp dowmload over");
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("FTP客户端出错!", e);
		} finally {
			try {
				os.close();
				ftpClient.logout();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException("关闭FTP连接发生异常!", e);
			}
		}
		return result;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值