package org.springblade.business.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
@Slf4j
public class FtpUtil {
private static FTPClient ftpClient = null;
public static FTPClient ftpConnection(String ip, String port, String username, String password) throws IOException {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ip, Integer.parseInt(port));
ftpClient.login(username, password);
int replyCode = ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(replyCode)) {
ftpClient.disconnect();
log.error("--ftp连接失败--");
System.exit(1);
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ftpClient;
}
public static void close(FTPClient ftpClient) throws IOException{
if(ftpClient!=null && ftpClient.isConnected()){
ftpClient.logout();
ftpClient.disconnect();
}
}
public static boolean downFile(FTPClient ftpClient, String newFileName, String fileName, String downUrl) throws IOException {
boolean isTrue = false;
OutputStream os = null;
try {
File localFile = new File(downUrl + "/" + newFileName);
if (!localFile.getParentFile().exists()) {
localFile.getParentFile().mkdirs();
localFile.createNewFile();
}
os = new FileOutputStream(localFile);
isTrue = ftpClient.retrieveFile(new String(fileName.getBytes(), "ISO-8859-1"), os);
if (isTrue) {
log.info("文件下载成功---------->>>>>文件名:" + fileName);
log.info("FTP文件下载成功!");
isTrue = true;
} else {
log.info("文件下载失败---------->>>>>文件名:" + fileName);
}
}catch (Exception e) {
log.error("FTP文件上传失败!", e);
} finally {
os.close();
close(ftpClient);
}
return isTrue;
}
public static void main(String[] args) throws IOException{
FTPClient ftpClient = ftpConnection("192.168.10.21","21","luyin","Luyin12#$");
boolean flag = downFile(ftpClient,"1446151.V3","/mnt/voice/1/0/20210311/1010/1446151.V3","E:/download");
System.out.println(flag );
}
}