1、引入依赖包
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.*;
2、连接ftp服务器
String server = "192.168.1.100";
int port = 21;
String user = "test";
String password = "password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
} catch (IOException ex) {
System.out.println("发生IO异常:" + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
3、上传文件
// 上传文件
String localFileToUpload = "D:\\test\\file.txt";
String remoteFileToUpload = "/test/file.txt";
boolean uploadSuccess = uploadFile(ftpClient, localFileToUpload, remoteFileToUpload);
if (uploadSuccess) {
System.out.println("文件上传成功!");
} else {
System.out.println("文件上传失败!");
}
public static boolean uploadFile(FTPClient ftpClient, String localFilePath, String remoteFilePath) throws IOException {
File localFile = new File(localFilePath);
InputStream inputStream = new FileInputStream(localFile);
try {
return ftpClient.storeFile(remoteFilePath, inputStream);
} finally {
inputStream.close();
}
}
4、下载文件
// 下载文件
String remoteFilePath = "/test/file.txt";
String localFilePath = "D:\\test\\other\\file.txt";
boolean downloadSuccess = downloadFile(ftpClient, remoteFilePath, localFilePath);
if (downloadSuccess) {
System.out.println("文件下载成功!");
} else {
System.out.println("文件下载失败!");
}
public static boolean downloadFile(FTPClient ftpClient, String remoteFilePath, String localFilePath) throws IOException {
File downloadFile = new File(localFilePath);
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
try {
return ftpClient.retrieveFile(remoteFilePath, outputStream);
} finally {
outputStream.close();
}
}