JAVA FTP上传下载文件
时间: 2024-10-29 21:05:37 浏览: 50
在Java中,通过Java的FTP客户端库,如Apache Commons Net,你可以方便地进行FTP文件的上传和下载操作。以下是基本步骤:
**上传文件(PUT):**
```java
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public void uploadFile(String host, int port, String username, String password, String remoteFilePath, File localFile) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(host, port);
ftpClient.login(username, password);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置二进制模式
// 上传文件到服务器
boolean uploaded = ftpClient.storeFile(remoteFilePath, new FileInputStream(localFile));
if (uploaded) {
System.out.println("文件 " + localFile.getName() + " 已成功上传至 " + remoteFilePath);
} else {
System.err.println("上传文件失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
```
**下载文件(GET):**
```java
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public void downloadFile(String host, int port, String username, String password, String remoteFilePath, File localDestination) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(host, port);
ftpClient.login(username, password);
// 检查文件是否存在
boolean fileExists = ftpClient.getFileList().stream()
.anyMatch(file -> file.getName().equals(remoteFilePath));
if (!fileExists) {
System.err.println("文件 " + remoteFilePath + " 不存在");
return;
}
ftpClient.enterLocalPassiveMode(); // 对于大型文件,启用被动模式避免防火墙问题
boolean downloaded = ftpClient.retrieveFile(remoteFilePath, new FileOutputStream(localDestination));
if (downloaded) {
System.out.println("文件 " + remoteFilePath + " 已成功下载至 " + localDestination.getAbsolutePath());
} else {
System.err.println("下载文件失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
```
阅读全文