java ftp下载文件
时间: 2023-08-31 12:11:15 浏览: 94
以下是使用Java实现FTP文件下载的示例代码:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FTPDownloadExample {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String pass = "password";
String remotePath = "/remote/path/file.txt";
String localPath = "/local/path/file.txt";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
OutputStream outputStream = new FileOutputStream(localPath);
InputStream inputStream = ftpClient.retrieveFileStream(remotePath);
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytesArray)) != -1) {
outputStream.write(bytesArray, 0, bytesRead);
}
boolean success = ftpClient.completePendingCommand();
if (success) {
System.out.println("File has been downloaded successfully.");
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
```
在上面的示例代码中,首先我们使用FTPClient连接到FTP服务器,然后登录并设置传输模式和文件类型。接下来,我们使用retrieveFileStream()方法从远程FTP服务器下载文件,将其保存到本地文件系统中。最后,我们使用completePendingCommand()方法告诉FTP服务器已经完成了文件传输。最后,记得关闭所有的流和连接。
阅读全文