1、pom中添加依赖
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
2、简单的工具类
package com.ouyin.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FTPUtil {
public static FTPClient connectFTP(String host, int port, String username, String password){
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(host, port);
//设置ftp连接模式 被动模式
ftpClient.enterLocalPassiveMode();
boolean login = ftpClient.login(username, password);
if (login) {
System.out.println(">>>>>>>>FTP-->downloadFile--登录成功>>>>>>>>>>>>>");
}
else {
System.out.println(">>>>>>>>FTP-->downloadFile--登录失败>>>>>>>>>>>>>");
throw new RuntimeException("FTP登陆失败,请检查用户信息!");
}
} catch (IOException e) {
e.printStackTrace();
}
return ftpClient;
}
public File downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName,FTPClient ftpClient) {
FileOutputStream outputStream = null;
File file = null;
try {
boolean isDownload = false;
file = new File(localPath + localFileName);
if (file.exists()) {
file.delete();
}
file.createNewFile();
//切换文件路径
ftpClient.makeDirectory(remotePath);
ftpClient.changeWorkingDirectory(remotePath);
FTPFile[] ftpFiles = ftpClient.listFiles();
for (FTPFile ftpFile : ftpFiles) {
if (ftpFile.getName().equals(remoteFileName)) {
outputStream = new FileOutputStream(file);
isDownload = ftpClient.retrieveFile(ftpFile.getName(), outputStream);
}
}
if (isDownload) {
System.out.println(">>>>>>>>FTP-->downloadFile--文件下载成功!本地路径:" + file);
}
else {
throw new RuntimeException("FTP-->downloadFile--文件下载失败!请检查!");
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
outputStream.close();
ftpClient.disconnect();
}
catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
public void uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName,FTPClient ftpClient) {
FileInputStream inputStream = null;
try {
//切换文件路径
ftpClient.makeDirectory(remotePath);
ftpClient.changeWorkingDirectory(remotePath);
inputStream = new FileInputStream(new File(localPath + localFileName));
//可上传多文件
boolean isUpload = ftpClient.storeFile(remoteFileName, inputStream);
if (isUpload) {
System.out.println(">>>>>>>>FTP-->uploadFile--文件上传成功!");
} else {
System.out.println(">>>>>>>>FTP-->uploadFile--文件上传失败!");
throw new RuntimeException("文件上传失败!");
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
inputStream.close();
ftpClient.disconnect();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}