Ftp DoGet 给出示例代码
时间: 2023-07-09 18:34:21 浏览: 62
以下是一个简单的 Java FTP Client,其中包含一个示例的 DoGet 方法来从 FTP 服务器上下载文件:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
public class FTPClientExample {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "your-username";
String pass = "your-password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
String remoteFile = "/path/to/remote/file.txt";
File localFile = new File("local-file.txt");
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
outputStream.close();
if (success) {
System.out.println("File downloaded successfully.");
} else {
System.out.println("Could not download file.");
}
ftpClient.logout();
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
```
其中的 DoGet 方法就是通过调用 FTPClient 的 retrieveFile 方法来从 FTP 服务器上下载文件。