如何用 Java 从 FTP 下载文件

一、流程概述

要从 FTP 下载文件,需要以下步骤:

步骤 操作
1 连接 FTP 服务器
2 切换到指定目录
3 下载文件
4 关闭连接

二、操作步骤及代码示例

1. 连接 FTP 服务器

引用形式的描述信息
// 创建 FTP 客户端
FTPClient ftpClient = new FTPClient();

// 连接 FTP 服务器
ftpClient.connect("ftp.example.com", 21);

// 登录
ftpClient.login("username", "password");

// 检查连接状态
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
    ftpClient.disconnect();
    throw new IOException("FTP server refused connection.");
}

2. 切换到指定目录

引用形式的描述信息
// 切换到指定目录
ftpClient.changeWorkingDirectory("/path/to/directory");

3. 下载文件

引用形式的描述信息
// 创建输出流
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("local-file.txt"));

// 下载文件
ftpClient.retrieveFile("remote-file.txt", outputStream);

// 关闭输出流
outputStream.close();

4. 关闭连接

引用形式的描述信息
// 关闭连接
ftpClient.logout();
ftpClient.disconnect();

三、状态图

stateDiagram
    [*] --> Connect
    Connect --> ChangeDirectory
    ChangeDirectory --> Download
    Download --> Close
    Close --> [*]

通过以上步骤,你就可以用 Java 从 FTP 下载文件了。希望这篇文章对你有所帮助!如果有任何疑问,欢迎随时向我提问。祝你学习进步!