java实现ftp上传下载
时间: 2023-10-19 10:09:28 浏览: 51
Java实现FTP上传下载可以使用Apache Commons Net库中的FTPClient类。以下是一个简单的示例代码:
```java
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.*;
public class FTPExample {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String password = "password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 上传文件
File localFile = new File("local-file.txt");
InputStream inputStream = new FileInputStream(localFile);
String remoteFile = "remote-file.txt";
boolean uploaded = ftpClient.storeFile(remoteFile, inputStream);
inputStream.close();
if (uploaded) {
System.out.println("文件上传成功!");
} else {
System.out.println("文件上传失败!");
}
// 下载文件
String downloadFile = "remote-file.txt";
File downloadLocalFile = new File("download-file.txt");
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadLocalFile)); boolean downloaded = ftpClient.retrieveFile(downloadFile, outputStream);
outputStream.close();
if (downloaded) {
System.out.println("文件下载成功!");
} else {
System.out.println("文件下载失败!");
}
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```