java实现ftp客户端
时间: 2023-07-28 11:35:53 浏览: 122
要实现一个 Java FTP 客户端,可以使用 Apache Commons Net 库。下面是一个简单的示例代码,可以连接到 FTP 服务器并下载文件:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPClientExample {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String password = "password";
String remoteFile = "/remote/file.txt";
String localFile = "local/file.txt";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, password);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("FTP server refused connection.");
return;
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
FileOutputStream outputStream = new FileOutputStream(localFile);
boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
outputStream.close();
if (success) {
System.out.println("File downloaded successfully.");
} else {
System.out.println("Failed to download file.");
}
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
```
这个示例代码连接到 FTP 服务器,登录,设置传输模式为二进制模式,下载文件并关闭连接。你可以根据你的需求修改代码。
阅读全文