import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class FTPExample {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String pass = "password";
FTPClient ftpClient = new FTPClient();
try {
// 连接到FTP服务器
ftpClient.connect(server, port);
// 登录到FTP服务器
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 下载文件
String remoteFile = "/remote/path/to/file.txt";
String localFilePath = "local/path/to/file.txt";
OutputStream outputStream = new FileOutputStream(localFilePath);
boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
outputStream.close();
if (success) {
System.out.println("文件下载成功");
} else {
System.out.println("文件下载失败");
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
导入必要的库:
org.apache.commons.net.ftp.FTP 和 org.apache.commons.net.ftp.FTPClient 是用于处理FTP连接的核心类。java.io.FileOutputStream 和 java.io.OutputStream 用于处理文件的输入输出流。创建FTP客户端实例:
FTPClient 类创建一个FTP客户端实例,用于与FTP服务器进行通信。连接和登录到FTP服务器:
connect 方法连接到指定的FTP服务器。login 方法登录到FTP服务器,提供用户名和密码。设置传输模式和文件类型:
enterLocalPassiveMode 设置为被动模式,以确保在防火墙后面也能正常工作。setFileType 设置文件传输类型为二进制模式(适合大多数文件类型)。下载文件:
retrieveFile 方法从远程服务器下载文件到本地路径。异常处理和资源释放:
上一篇:java map转json字符串
下一篇:java <<
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站