1、依赖引入
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version>
</dependency>
2、案例代码
package work.vcloud.scan.util.ftp;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@Component
public class FtpUtil {
private static final int CONNECT_TIMEOUT = 60 * 1000;
@Value("${ftp.host}")
private String host;
@Value("${ftp.port}")
private Integer port;
@Value("${ftp.userName}")
private String userName;
@Value("${ftp.password}")
private String password;
private FTPClient getFtpClient() throws Exception {
FTPClient ftpClient = new FTPClient();
ftpClient.setConnectTimeout(CONNECT_TIMEOUT);
ftpClient.connect(host, port);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new Exception("FTP connection failed with reply code: " + reply);
}
boolean success = ftpClient.login(userName, password);
if (!success) {
throw new Exception("FTP login failed.");
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.enterLocalPassiveMode();
return ftpClient;
}
public boolean download(String path, String filename, OutputStream outputStream) throws Exception {
FTPClient ftpClient = getFtpClient();
try {
ftpClient.changeWorkingDirectory(path);
ftpClient.retrieveFile(filename, outputStream);
outputStream.flush();
outputStream.close();
ftpClient.logout();
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
}
return false;
}
public boolean upload(String path, String filename, InputStream inputStream) throws Exception {
FTPClient ftpClient = getFtpClient();
try {
boolean flag = ftpClient.changeWorkingDirectory(path);
if (!flag) {
ftpClient.makeDirectory(path);
ftpClient.changeWorkingDirectory(path);
}
ftpClient.storeFile(filename, inputStream);
inputStream.close();
ftpClient.logout();
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
}
return false;
}
public void listFtpFile(String path) throws Exception {
FTPClient ftpClient = getFtpClient();
try {
ftpClient.changeWorkingDirectory(path);
FTPFile[] files = ftpClient.listFiles("./");
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getName());
}
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
}
}
}