生成一段JAVA,FTP下载文件的代码
时间: 2024-05-03 13:22:50 浏览: 11
以下是使用Apache Commons Net库实现FTP下载文件的JAVA代码:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FTPDownloader {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String pass = "password";
String remoteFilePath = "/remote/file/path/file.txt";
String localFilePath = "C:/local/file/path/file.txt";
FTPClient ftpClient = new FTPClient();
try {
// Connect to FTP server
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// Download file
InputStream inputStream = ftpClient.retrieveFileStream(remoteFilePath);
FileOutputStream outputStream = new FileOutputStream(localFilePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
// Logout and disconnect from FTP server
ftpClient.logout();
ftpClient.disconnect();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在代码中,您需要替换以下变量:
- `server` - FTP服务器的地址
- `port` - FTP服务器的端口
- `user` - 登录FTP服务器的用户名
- `pass` - 登录FTP服务器的密码
- `remoteFilePath` - 要下载的远程文件的路径和文件名
- `localFilePath` - 要保存到本地的文件的路径和文件名
您还需要在项目中包含Apache Commons Net库的依赖项。可以使用Maven添加以下依赖项:
```xml
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.7</version>
</dependency>
```