Java FTP客户端工具类实现
本工具类封装了Java连接FTP服务器进行文件下载的核心功能,提供简洁易用的API接口。
功能特点:
- 支持自定义FTP服务器地址、端口、用户名及密码。
- 支持指定远程FTP文件路径及本地保存路径。
使用方法:
- 创建
FtpClientUtil
实例,传入FTP服务器连接信息。 - 调用
downloadFile()
方法,传入远程文件路径和本地保存路径,执行文件下载操作。
代码示例:
import org.apache.commons.net.ftp.FTPClient;
// ...其他必要的import语句
public class FtpClientUtil {
private String ftpHost;
private int ftpPort;
private String ftpUsername;
private String ftpPassword;
// 构造函数,初始化FTP连接信息
public FtpClientUtil(String ftpHost, int ftpPort, String ftpUsername, String ftpPassword) {
this.ftpHost = ftpHost;
this.ftpPort = ftpPort;
this.ftpUsername = ftpUsername;
this.ftpPassword = ftpPassword;
}
// 下载文件方法
public boolean downloadFile(String remoteFilePath, String localFilePath) {
FTPClient ftpClient = new FTPClient();
try {
// 连接FTP服务器
ftpClient.connect(ftpHost, ftpPort);
ftpClient.login(ftpUsername, ftpPassword);
// 设置文件传输模式
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 下载文件
try (OutputStream outputStream = new FileOutputStream(localFilePath)) {
ftpClient.retrieveFile(remoteFilePath, outputStream);
}
return true;
} catch (IOException e) {
// 处理异常
e.printStackTrace();
return false;
} finally {
// 断开FTP连接
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
使用示例:
// 创建FtpClientUtil实例
FtpClientUtil ftpClientUtil = new FtpClientUtil("your_ftp_host", 21, "your_username", "your_password");
// 下载文件
boolean success = ftpClientUtil.downloadFile("/remote/file/path.txt", "/local/file/path.txt");
// 检查下载是否成功
if (success) {
System.out.println("文件下载成功!");
} else {
System.out.println("文件下载失败!");
}
注意:
- 请替换代码中的占位符为实际的FTP服务器连接信息和文件路径。
- 该工具类使用了Apache Commons Net库,请确保项目中已引入该依赖。
6.74KB
文件大小:
评论区