FTP连接工具

FTP连接工具

实现

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import com.ctid.core.exception.ServiceException;
import com.ctid.mainlib.system.util.datehandle.PathHandler;

/**
 * @功能描述 FTP客户端
 * @author 索睿君
 * @date 2019年6月11日14:36:11
 */
public class FtpHandle implements AutoCloseable{
	private static final Log Log = LogFactory.getLog(FtpHandle.class);
	private FTPClient ftpClient;
	
	/**
	 * @功能描述 通过构造函数创建FTP连接对象
	 * @param host 主机
	 * @param port 端口
	 * @param username 账号
	 * @param password 密码
	 * @param timeout 超时时间
	 * @throws IOException 
	 * @throws SocketException
	 */
	public FtpHandle(String host, int port, String username, String password, int timeout) throws Exception {
		super();
		//创建FTP连接
		this.ftpClient = new FTPClient();
		this.ftpClient.setBufferSize(8192);
		this.ftpClient.setConnectTimeout(timeout);
		this.ftpClient.connect(host, port);
		this.ftpClient.setDataTimeout(timeout);
		this.ftpClient.setSoTimeout(timeout);
		if(!FTPReply.isPositiveCompletion(this.ftpClient.getReplyCode())){
			this.ftpClient.disconnect();
			throw new ServiceException("创建FTP连接失败, 返回码: " + this.ftpClient.getReplyCode());
		}
		if(!this.ftpClient.login(username, password)){
			this.ftpClient.disconnect();
			throw new ServiceException("创建FTP连接失败, 登录失败!");
		}
		this.ftpClient.enterLocalPassiveMode();
	}

	
	/**
	 * @功能描述 获取指定文件夹下的文件名称集合
	 * @param folder 文件夹
	 * @return 返回文件名称集合
	 * @throws ServiceException 
	 */
	public List<String> getFileNameList(String folder) throws ServiceException{
		try {
			//设置文件类型为二进制文件
			this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			//获取FTP路径下的文件集合
			List<FTPFile> ftpFileList = Arrays.asList(this.ftpClient.listFiles(folder));
			//迭代FTP文件集合, 将文件名存入新的文件名称集合
			ArrayList<String> fileNameList = new ArrayList<String>();
			ftpFileList.forEach(ftpFile -> fileNameList.add(ftpFile.getName()));
			return fileNameList;
		} catch (IOException e) {
			throw new ServiceException("获取指定文件夹下的文件名称集合执行异常, " + e.toString());
		}
	}
	
	/**
	 * @功能描述 验证文件是否存在
	 * @param path 路径
	 * @return 返回验证结果
	 * @throws ServiceException 
	 */
	public boolean isFile(String path) throws ServiceException{
		try {
			//设置文件类型为二进制文件
			this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			FTPFile[] files = this.ftpClient.listFiles(path);
			return files != null && files.length > 0;
		} catch (IOException e) {
			return false;
		}
	}
	
	/**
	 * @功能描述 验证路径是否存在
	 * @param directory 目录
	 * @return 返回验证结果
	 */
	public boolean isDire(String directory){
		try {
			return this.ftpClient.changeWorkingDirectory(directory);
		} catch (IOException e) {
			return false;
		}
	}
	
	/**
	 * @功能描述 将FTP文件导入到本地
	 * @param ftpPath
	 * @param localPath
	 * @return
	 * @throws IOException
	 */
	public boolean fileImport(String ftpPath, String localPath) throws ServiceException{
		//本地路径合法化
		File file = PathHandler.initPath(localPath);
		try(FileOutputStream out = new FileOutputStream(file, true)) {
			//设置文件类型为二进制文件
			this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			FTPFile[] ftpFiles = this.ftpClient.listFiles(ftpPath);
			//如果读取到多个文件或者没有读取到文件则抛出异常
			if(ftpFiles == null || ftpFiles.length != 1){
				throw new ServiceException("FTP文件导出执行异常, 读取文件异常");
			}
			//如果FTP文件比本地文件小, 则中断读取
			if (file.length() >= ftpFiles[0].getSize()) {
				return false;
			}
			//如果本地文件存在数据则根据本地文件大小移动FTP文件指针进行断点读取
			if(file.length() > 0){
				this.ftpClient.setRestartOffset(file.length());
			}
			return this.ftpClient.retrieveFile(ftpPath, out);
		} catch (Exception e) {
			Log.error("将FTP文件导入到本地执行异常, 异常信息: " + e.toString());
			return false;
		}
	}
	
	/**
	 * @功能描述 将本地文件导出到FTP
	 * @param ftpPath ftp路径
	 * @param localPath 本地路径
	 * @return
	 * @throws ServiceException 
	 * @throws Exception
	 */
	public boolean fileExport(String ftpPath, String localPath) throws ServiceException {
		try {
			this.ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			//获取FTP文件名
			String fileName = ftpPath.substring(ftpPath.lastIndexOf("/") + 1);
			//获取FTP目录
			String directory = ftpPath.substring(0, ftpPath.lastIndexOf("/") + 1);
			//初始化FTP目录
			initPath(directory);
			// 检查远程是否存在文件
			FTPFile[] files = ftpClient.listFiles(ftpPath);
			if(files.length > 0 && files[0].getSize() >= new File(localPath).length()){
				this.ftpClient.deleteFile(fileName);
			}
			InputStream inputStream = new FileInputStream(localPath);
			return this.ftpClient.storeFile(fileName, inputStream);
		} catch (Exception e) {
			return false;
			//throw new ServiceException("FTP文件导入执行异常, " + e.toString());
		}
	}
	
	/**
	 * @功能描述 初始化FTP路径
	 * @param directory 目录
	 * @param fileName 文件名
	 * @return 
	 * @throws ServiceException 
	 */
	public boolean initPath(String directory) throws ServiceException {
		try {
			if (ftpClient.changeWorkingDirectory(directory)) {
				return true;
			}
			//跳转到根目录
			this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			this.ftpClient.changeWorkingDirectory(File.separator);
			//将目录分割为数组
			String[] directorys = directory.split("/");
			//迭代目录数组, 创建目录
			for (String dir : directorys) {
				//判断当前目录是否可用打开
				if(!ftpClient.changeWorkingDirectory(dir)){
					//创建目录, 创建成功后跳转到创建好的目录
					if(this.ftpClient.makeDirectory(dir)){
						ftpClient.changeWorkingDirectory(dir);
					}
				}
			}
			return true;
		} catch (Exception e) {
			throw new ServiceException("初始化FTP目录执行异常, " + e.toString());
		}
	}
	/**
	 * @功能描述 移动文件, 或者重命名文件
	 * @param srcPath
	 * @param targetPath
	 * @return
	 * @throws IOException
	 * @throws ServiceException 
	 */
	public boolean refileName(String srcPath, String targetPath) throws ServiceException {
		try {
			return ftpClient.rename(srcPath, targetPath);
		} catch (Exception e) {
			throw new ServiceException("移动文件, 或者重命名文件执行异常, " + e.toString());
		}
	}
	
	/**
	 * @功能描述 切换到FTP根目录
	 * @throws ServiceException
	 */
	public void rootPath() throws ServiceException{
		try {
			//设置文件类型为二进制文件
			this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			this.ftpClient.changeWorkingDirectory(File.separator);
		} catch (IOException e) {
			throw new ServiceException("切换到FTP根目录执行异常, " + e.toString());
		}
	}


	/**
	 * @功能描述 关闭FTP连接, 退出登录
	 */
	@Override public void close(){
		try {
			if(this.ftpClient != null) {
				this.ftpClient.logout();
			}
			if(this.ftpClient != null && this.ftpClient.isConnected()) {
				this.ftpClient.disconnect();
			}
		} catch (IOException e) {
			Log.error("关闭FTP连接执行异常, 异常信息: " + e.toString());
		}
    }
}

使用

	public static void main(String[] args) {
		String host = "172.18.2.239";						//主机
		int port = 22;										//端口
		String username = "CTCC";							//用户名
		String password = "**************";					//密码
		int timeout = 10000;								//超时时间
		try(FtpHandle ftpHandle = new FtpHandle(host , port, username, password, timeout)) {
			ftpHandle.fileExport("FTP路径", "本地路径");	//上传文件到FTP
			ftpHandle.fileImport("FTP路径", "本地路径");	//下载文件到本地
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值